当我运行以下代码时,我得到
collect2: fatal error: cannot find 'ld'
compilation terminated.输出。我的海湾合作委员会版本是gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0. 似乎无法找到ld模块。我不知道如何继续前进。
#define _GNU_SOURCE
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(){
char *stderr = "/home/vs/Desktop/test/output.txt";
char *args[] = {"/usr/bin/gcc",
"-Wall",
"-O2",
"-std=gnu11",
"-fomit-frame-pointer",
"/home/vs/Desktop/test/Solution.c",
"-o",
"/home/vs/Desktop/test/Solution",
"-lm",
NULL};
char *env[] = {"LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8", NULL};
int fd;
if(0 > (fd = open(stderr, O_WRONLY|O_TRUNC))) perror("open");
if(0 > dup2(fd, 2)) perror("dup");
if(fd != 2) close(fd);
int x = execve("/usr/bin/gcc", args, env);
printf("%d\n", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于相同的编译命令在通过 shell 发出时有效,但在以编程方式发出时失败(如图所示),因此问题很可能与您提供的环境有关execve()。特别注意,提供给该函数的环境数组代表命令的整个环境,而不仅仅是额外的条目。
在这方面特别相关的是所提供的环境不包括变量PATH。因此,执行进程将需要使用它想要依次启动的任何命令的完全限定路径,例如ld. 如果不这样做,那么就会出现您报告的错误。将 a 添加PATH到指定环境应该可以解决该问题。您可以从程序自己的环境中复制它,或者更容易地插入默认路径。例如,
// ...
char *env[] = {
"PATH=/usr/local/bin:/usr/bin:/bin", // <--- this
"LANG=en_US.UTF-8",
"LANGUAGE=en_US:en",
"LC_ALL=en_US.UTF-8",
NULL
};
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6309 次 |
| 最近记录: |