为什么带有静态main()类型的程序显示错误?

kap*_*pil -5 c c++

#include<stdio.h>
static int main()
{
   printf("foo");
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码给出了错误

nfo): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

错误背后的原因是什么?

das*_*ght 7

在C中,static是"隐藏"实现细节的主要方式.static在C中标记函数或变量意味着将其可见性限制为定义它的转换单元.实质上,只有同一个C文件中的函数才能引用它们.其他文件或库中的函数无法访问它们.

因为main需要从你的环境的启动代码(一段代码"引导你的程序执行")中访问函数,所以隐藏它会使你的程序无法链接:编译器试图查找main,但它是隐藏的,所以链接器发出一个错误.