C语言 C 链接错误:未定义对“main”的引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15905119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C Linking Error: undefined reference to 'main'
提问by Nicole
I have read the other answers on this topic, and unfortunately they have not helped me. I am attempting to link several c programs together, and I am getting an error in response:
我已经阅读了关于这个主题的其他答案,不幸的是他们没有帮助我。我试图将几个 c 程序链接在一起,但我收到一个错误响应:
$ gcc -o runexp.o scd.o data_proc.o -lm -fopenmp
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make: * [runexp] Error 1
I have exactly one main function and it is in runexp. The form is
我只有一个 main 函数,它在 runexp 中。表格是
int main(void) {
...;
return 0;
}
Any thoughts on why I might get this error? Thanks!
关于为什么我可能会收到此错误的任何想法?谢谢!
采纳答案by VHaravy
You should provide output file name after -ooption. In your case runexp.ois treated as output file name, not input object file and thus your mainfunction is undefined.
您应该在-o选项后提供输出文件名。在您的情况下runexp.o被视为输出文件名,而不是输入目标文件,因此您的main函数未定义。
回答by unwind
You're not including the C file that contains main()when compiling, so the linker isn't seeing it.
您不包括main()编译时包含的 C 文件,因此链接器看不到它。
You need to add it:
你需要添加它:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
回答by Bechir
You are overwriting your object file runexp.oby running this command :
您正在runexp.o通过运行以下命令覆盖目标文件:
gcc -o runexp.o scd.o data_proc.o -lm -fopenmp
In fact, the -ois for the outputfile.
You need to run :
实际上,-o是用于输出文件。你需要运行:
gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp
runexp.outwill be you binary file.
runexp.out将是你的二进制文件。
回答by Jordan Effinger
Generally you compile most .c files in the following way:
通常,您通过以下方式编译大多数 .c 文件:
gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:
gcc foo.c -o foo.c 它可能会有所不同,具体取决于您使用的 #includes 或您是否有任何外部 .h 文件。一般来说,当你有一个 C 文件时,它看起来有点像下面这样:
#include <stdio.h>
/* any other includes, prototypes, struct delcarations... */
int main(){
*/ code */
}
When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main()in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:
当我收到“对 main 的未定义引用”时,通常意味着我有一个文件中没有的 .cint main()文件。如果您第一次学习 Java,这是一种可以理解的混淆方式,因为在 Java 中,您的代码通常如下所示:
//any import statements you have
public class Foo{
int main(){}
}
I would advise looking to see if you have int main()at the top.
我建议看看你是否int main()在顶部。

