简体   繁体   English

C / XCode:sh:./child:没有这样的文件或目录。 命令在终端中运行,但不在XCode中运行

[英]C/XCode: sh: ./child: No such file or directory. Command runs in terminal but not XCode

So I have a child.c file and I want to compile and run it in my main.c file using the system() function of stdlib.h. 所以我有一个child.c文件,我想使用stdlib.h的system()函数在main.c文件中编译并运行它。

child.c: child.c:

#include<stdio.h>
int main(){
printf("I am the child\n");
return 0;
}

main.c: main.c中:

#include <stdio.h>
#include <stdlib.h>

int main() {
    system("cd ~/Desktop/HW3/HW3");
    system("gcc -o child child.c");
    system("./child");
    return 0;
}

everything worked fine when I compile and run main.c in terminal using the following command 使用以下命令在终端中编译并运行main.c时,一切正常

abcs-mbp:HW3 abc$ cd
abcs-mbp:~ abc$ cd ~/Desktop/HW3/HW3
abcs-mbp:HW3 abc$ gcc -o main main.c
abcs-mbp:HW3 abc$ ./main

and it ran child.c and printed the following: 它运行child.c并打印以下内容:

I am the child

but when I tried to run the exact same main.c in XCode, XCode gave me the following error: 但是,当我尝试在XCode中运行完全相同的main.c时,XCode给了我以下错误:

clang: error: no such file or directory: 'child.c'
clang: error: no input files
sh: ./child: No such file or directory

anybody know why this is happening? 有人知道为什么会这样吗? I think it has something to do with path, but how can I tell XCode the path of child.c and then tell it to compile child.c? 我认为这与路径有关,但是如何告诉XCode child.c的路径,然后告诉它编译child.c?

I also tried 我也试过

 system("cd ~/Desktop/HW3/HW3");
 system("gcc -o child child.c");
 system("./child");

and

system("/Users/vqianxiao/Desktop/HW3/HW3/ gcc -o child child.c");

but nothing seems to work... any help is appreciated! 但似乎无济于事...感谢您的帮助!

the reason that it does not work is a combination of things 它不起作用的原因是多种因素的结合

1) each 'system' call is run in a separate shell instance, 
   so the second 'system' call 
   starts from the directory where the main program is running.

2) things do down from there

a suggested fix: 建议的修复方法:

system("cd ~/Desktop/HW3/HW3; && gcc -o child child.c; && ./child;");

notice, all one system call, terminators at end of commands, and linked by && so one command must be successful to continue on to the next command 注意,所有一个系统调用,命令末尾的终止符,并由&&链接,因此一个命令必须成功才能继续执行下一个命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM