C++ 编译错误:未定义符号:“_main”,引用自:从 crt1.10.5.o 开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/550455/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:54:30  来源:igfitidea点击:

Compile error: Undefined symbols: "_main", referenced from: start in crt1.10.5.o

c++

提问by FurtiveFelon

I have the following code:

我有以下代码:

#include <iostream>

using namespace std;

class testing{
   int test() const;
   int test1(const testing& test2);
};

int testing::test() const{
   return 1;
}

int testing::test1(const testing& test2){
   test2.test();
   return 1;
}

after compilation, it gives me the following error:

编译后,它给了我以下错误:

Undefined symbols:
  "_main", referenced from:
      start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Why is it complaining about main? Can't i declare main in another file and include this one?

为什么它抱怨主要?我不能在另一个文件中声明 main 并包含这个文件吗?

Thanks a lot!

非常感谢!

回答by Johannes Schaub - litb

You have tried to link it already:

您已经尝试链接它:

g++ file.cpp

That will not only compile it, but try to already create the executable. The linker then is unable to find the main function that it needs. Well, do it like this:

这不仅会编译它,还会尝试创建可执行文件。然后链接器无法找到它需要的主函数。好吧,这样做:

g++ -c file.cpp
g++ -c hasmain.cpp

That will create two files file.o and hasmain.o, both only compiled so far. Now you can link them together with g++:

这将创建两个文件 file.o 和 hasmain.o,这两个文件目前都只编译过。现在您可以使用 g++ 将它们链接在一起:

g++ -omy_program hasmain.o file.o

It will automatically figure out that those are files already compiled, and invoke the linker on them to create a file "my_program" which is your executable.

它会自动找出那些已经编译的文件,并调用它们的链接器来创建一个文件“my_program”,它是你的可执行文件。

回答by Himadri Choudhury

If you declare the main function in another file, then you must compile the two files separately, and then link them into 1 executable.

如果在另一个文件中声明 main 函数,则必须分别编译这两个文件,然后将它们链接成 1 个可执行文件。

Unless you include the entire contents of the file from the file with the main function, that will work too, though a bit odd. But, if you do this then you have to make sure that you compile the file which has the main() function.

除非您使用 main 函数包含文件中文件的全部内容,否则它也可以工作,尽管有点奇怪。但是,如果您这样做,那么您必须确保编译具有 main() 函数的文件。