在我的编译器课程中,我将遵循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
传递给编译器