我正在使用 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,但未找到 liblto_plugin.so。编译已终止。”我认为这意味着正在编译 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
关于使用 exec() 编译和运行 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35371135/