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

时间:2015-02-22 15:59:12

标签: c++ c

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

代码给出了错误

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

错误背后的原因

3 个答案:

答案 0 :(得分:7)

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

因为需要从你的环境的启动代码(一段代码“引导你的程序执行”)访问函数main,所以隐藏它会使你的程序不可链接:编译器试图找到{{1但是它是隐藏的,因此链接器会发出错误。

答案 1 :(得分:3)

它显示错误,因为您的程序中没有正确的主函数。在C和C ++中,main()不能是静态的。 static存储说明符表示该函数仅在此转换单元中可见,并且C运行时环境无法访问它:

prog.c:3:12: warning: 'main' is normally a non-static function [-Wmain]
 static int main()
            ^
prog.c:3:12: warning: 'main' defined but not used [-Wunused-function]
/usr/lib/gcc/i586-linux-gnu/4.9/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status

答案 2 :(得分:1)

static int main()在C或C ++中都不是正确的签名。 C ++中main的签名

int main() { / ... / } 
int main(int argc, char* argv[]) { / ... / }  

在C

int main(void) { / ... / } 
int main(int argc, char* argv[]) { / ... / }