0

我知道可能会有类似的问题,只是它们是在C++中的,我不知道它们是否相同。我有一些代码

void BuildApp(char *AppName)
{
        char *cmd;
        cmd = combine("mkdir ./Projects/", AppName);
        cmd = combine(cmd, "/Package/");
        // Make the package dir.
        system(cmd);
        cmd = "";
        cmd = combine("mkdir ./Projects/", AppName);
        cmd = combine(cmd, "/Package/DEBIAN");
        system(cmd);
        cmd = "";
        cmd = combine("mkdir ./Projects/", AppName);
        cmd = combine(cmd, "/Package/Applications");
        system(cmd);
        cmd = "";
        cmd = combine("mkdir ./Projects/", AppName);
        cmd = combine(cmd, "/Package/Applications/");
        cmd = combine(cmd, AppName);
        cmd = combine(cmd, ".app");
        system(cmd);
        cmd = "";
        cmd = combine("mkdir ./Projects/", AppName);
        cmd = combine(cmd, "/Package/Applications/");
        cmd = combine(cmd, AppName);
        cmd = combine(cmd, ".app/Inc");
        system(cmd);
        cmd = "";
        cmd = combine("cp ./Projects/", AppName);
        cmd = combine(cmd, "/Assets/app.icon.png ./Projects/");
        cmd = combine(cmd, AppName);
        cmd = combine(cmd, "/Package/Applications/");
        cmd = combine(cmd, AppName);
        cmd = combine(cmd, ".app/Icon.png");
        system(cmd);
        printf("Building application...");
        cmd = "";
        cmd = combine("cd ./Projects/", AppName);
        system(cmd);
        printf(cmd);
        cmd = "";
        cmd = combine("gcc App.c -o ", AppName);
        printf(cmd);system(cmd);
        system(cmd);
}

但它似乎执行不正常。这是在 Linux(实际上是 cygwin)上运行的,并使用 GCC 编译。出于某种原因,system();应该执行 GCC 编译操作的函数在cd命令之前执行,给我这个输出:

gcc: App.c: No such file or directory
gcc: no input files
Building application...
cd ./Projects/Sample

但是,在cd声明之后(我打印出来检查它们执行的顺序),GCC 编译命令没有执行,给我留下一个未编译的 App.c,并且程序执行出错。任何有关为什么会发生这种情况的帮助将不胜感激。

4

2 回答 2

7

你有两个“问题”:

  • 您看到的输出来自stderr(GCC 错误消息)和stdout(其余部分)。您推断这些消息出现在您的终端上的顺序与生成它们的代码运行的顺序相同 - 您不能依赖它。stdout通常是缓冲的,而stderr通常不是,因此它们出现在屏幕上的顺序并不是代码执行顺序的指标。
  • The system("cd whatever"); call is a bug. It spawns a new shell, that shell changes directories and... promptly exists. It has no side-effect whatsoever on the parent process or the subsequent system calls. You need to use chdir in the parent process, or do the cd and gcc in the same system call.
于 2012-04-14T08:43:46.720 回答
2

每个system命令都作为一个单独的进程执行。您更改了刚刚结束的新流程的工作。它对下一个执行的流程没有影响。

采用system("cd dir; command");

于 2012-04-14T08:43:45.297 回答