c-gcc链接两个文件在macOS中不起作用



在我的编译器课程中,我将遵循Abdulaziz Ghuloum的编译器构造增量方法及其附带教程。在某些情况下,我们有以下两个.c文件:

runtime.c

#include <stdio.h>
int main(int argc, char** argv) {
printf("%dn", entry_point());
return 0;
}

ctest.c

int entry_point() {
return 7;
}

然后作者运行以下命令:

$ gcc -Wall ctest.c runtime.c -o test
[bunch of warnings]
$ ./test
7
$

但当我运行$ gcc -Wall ctest.c runtime.c -o test时,我会得到以下错误:

runtime.c:9:20: error: implicit declaration of function 'entry_point' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
printf("%dn", entry_point());

我希望能够像作者使用gcc那样编译和链接我的两个.c文件,但它一直给我带来错误。我一直在做一些研究,但同样的命令($ gcc file1.c file2.c -o combined(不断出现。我们将不胜感激。

我在MacOS Monterey 12.6上运行这个,并进行gcc --version显示:

Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

提前感谢

在macOS上,默认编译器是clang,而不是gcc。后者只是clang的符号链接,因此需要记住这一点。

Clang在runtime.c中看到了对entry_point()的调用,但还不知道。对于这样一个未定义的函数,传统的C是假设它返回int并且不接受参数。但默认情况下,Clang走的是安全路线,而不仅仅是警告,而是将其视为错误,因为大多数时候这种假设都是错误的,可能会导致运行时问题。

您有多种选择:

  • runtime.c中添加一个定义int entry_point(void);#include的头文件
  • runtime.c顶部附近添加行int entry_point(void);
  • -Wno-error=implicit-function-declaration传递给编译器

最新更新