简体   繁体   English

`没有main()的Cpp类中对`main`的未定义引用

[英]`undefined reference to `main` in Cpp class without main()

I came across this while trying to get an answer. 我试图找到答案时遇到了这个问题。 But it seems like the poster had multiple files and they were not getting linked, and hence the error. 但似乎海报有多个文件,而且它们没有被链接,因而错误。

But, why do I get this error when using a single file? 但是,为什么在使用单个文件时会出现此错误?

g++ myClass.cpp  
/usr/lib/gcc/i686-redhat-linux/4.6.3/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status

And why is main necessary here at compile time ( from where does it find a mention of main in my code ) ? 为什么在编译时main需要( 从哪里可以看到我的代码中提到main )? main is the starting point of code execution, but why does the compiler assume i need a main here. main是代码执行的起点,但为什么编译器假设我需要一个main I can have it defined in some other file and use gcc -o to make an executable? 我可以在其他文件中定义它并使用gcc -o制作可执行文件吗?

Or maybe I am missing something else in the code which causes the error? 或者我可能在代码中遗漏了导致错误的其他内容?

#include<iostream>
class myClass
{

public:
myClass()
{
    std::cout<<"Constructor";
}

~myClass()
{
    std::cout<<"Destructor";    
}

};

You are trying to compile an executable, so a main function is expected. 您正在尝试编译可执行文件,因此需要一个main函数。 You should compile an object file by using the -c flag: 您应该使用-c标志编译目标文件:

g++ -c myClass.cpp

While you are at it, I suggest adding warning flags -Wall -Wextra at the very least. 当你在这里时,我建议至少添加警告标志-Wall -Wextra

main is not necessary to compile a source file. main不需要编译源文件。 It is necessary to link a program into an executable [1], because the program has to start somewhere. 有必要将程序链接到可执行文件[1],因为程序必须从某个地方开始。

You need to tell the compiler that "this is not the whole of my program, just compile, but don't link", using the '-c' option, so 你需要告诉编译器“这不是我的整个程序,只是编译,但不要链接”,使用'-c'选项,所以

g++ -c myClass.cpp

which will produce a myClass.o file that you can then use later, eg 这将生成一个myClass.o文件,您可以稍后使用,例如

g++ -o myprog myClass.o myOtherClass.o something_that_has_main.o -lsomelib

(Obviously, substitute names with whatever you have in your project) (显然,用项目中的任何内容替换名称)

[1] Assuming you use the regular linker scrips that come with the compiler. [1]假设您使用编译器附带的常规链接器scrips。 There are "ways around that too", but I think that's beyond this answer. 还有“解决方法”,但我认为这超出了这个答案。

You are building your source as an application. 您正在将源代码构建为应用程序。 Add -c option to produce only object file: 添加-c选项以仅生成目标文件:

g++ -c myClass.cpp

Compile only?! 仅编译?! use -c option 使用-c选项

g++ -c file.cpp

otherwise the project needs a main . 否则项目需要一个main

You need to use the -c flag to compile and only tell the compiler to generate an object file. 您需要使用-c标志进行编译,并且只告诉编译器生成目标文件。 You're telling the compiler to make an executable. 你告诉编译器生成一个可执行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM