起因是我突然发现用 GCC 不带任何编译选项来编译下面的 C 代码,会报错:
#include <stdio.h> inline void func() { printf("Hello world!\n"); } int main() { func(); return 0; } 错误输出:
/usr/bin/ld: /tmp/ccdw5O1b.o: in function `main': test.c:(.text+0xe): undefined reference to `func' collect2: error: ld returned 1 exit status 但是,用 G++ 不带任何编译选项编译下面的 C++ 代码,正常运行:
#include <iostream> using namespace std; inline void func() { cout << "Hello world!" << endl; } int main() { func(); return 0; } 我把 C 代码中的 func 加上 static 修饰符,可以正常编译:
#include <stdio.h> static inline void func() { printf("Hello world!\n"); } int main() { func(); return 0; } 用 inline 声明 func 也可以正常编译:
#include <stdio.h> inline void func(); void func() { printf("Hello world!\n"); } int main() { func(); return 0; } 编译的时候加上 -O2 选项也能正常编译。
我查了很多的博客,包括 C11 的标准文件,但是迫于理解能力,还是没能搞懂为啥会这样,所以在此请教一下大家。
附上我查的资料链接:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
https://stackoverflow.com/questions/19068705/undefined-reference-when-calling-inline-function
https://stackoverflow.com/questions/16245521/c99-inline-function-in-c-file/16245669#16245669
https://runtimeverification.com/blog/undefined-c-common-mistakes/
