使用 exec() 编译和 运行 一个 c 程序

compiling and running a c program using exec()

我正在编写一个使用 execv() 编译的程序,运行 是另一个程序。我编写了一个名为 helloWorld.c 的简单 C 程序,当执行输出时,"Hello world," 和第二个名为 testExec.c 的文件应该编译和 运行 helloWorld.c.我一直在到处寻找方法来做到这一点,但我还没有找到任何答案。 testExec.c中的代码是:

#include <stdio.h>
#include <unistd.h>
int main(){
   char *args[] = {"./hellWorld.c", "./a.out", NULL};
   execv("usr/bin/cc", args);
   return 0;
}

testExec.c 编译没有错误。但是,当我 运行 时,我收到一条错误消息,上面写着 "fatal error: -fuse-linker-plugin, but liblto_plugin.so not found. compilation terminated." 我认为这意味着 helloWorld.c 正在编译,但是当需要 运行 helloWorld.c抛出此错误。我想也许那是因为我有 a.out 和 helloWorld.c 以 './' 开头。我从两者中删除了'./',然后分别删除了其中一个,但仍然没有运气。

我也做了 'sudo apt-get install build-essential' 和 'sudo apt-get install gcc'。我不确定这是否能解决问题,但我真的不确定还能尝试什么。无论如何,我们将不胜感激!

您在调用 cc 时缺少前导斜杠。

此外,参数列表中的第一个参数是可执行文件的名称。实际的论点在那之后。您也没有使用 -o 来指定输出文件的名称。

#include <stdio.h>
#include <unistd.h>
int main(){
   char *args[] = {"cc", "-o", "./a.out", "./hellWorld.c", NULL};
   execv("/usr/bin/cc", args);
   return 0;
}

编辑:

以上仅编译。如果你想编译和运行,你可以这样做:

#include <stdio.h>
#include <unistd.h>
int main(){
   system("cc -o ./a.out ./hellWorld.c");
   execl("./a.out", "a.out", NULL);
   return 0;
}

虽然这可能最好作为 shell 脚本完成:

#!/bin/sh

cc -o ./a.out ./hellWorld.c
./a.out