Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`undefined reference to `main` in Cpp class without main()

Tags:

c++

g++

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 is the starting point of code execution, but why does the compiler assume i need a main here. I can have it defined in some other file and use gcc -o to make an executable?

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";    
}

};
like image 431
Suvarna Pattayil Avatar asked Apr 26 '13 13:04

Suvarna Pattayil


2 Answers

main is not necessary to compile a source file. It is necessary to link a program into an executable [1], because the program has to start somewhere.

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

g++ -c myClass.cpp

which will produce a myClass.o file that you can then use later, e.g.

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. There are "ways around that too", but I think that's beyond this answer.

like image 111
Mats Petersson Avatar answered Oct 19 '22 15:10

Mats Petersson


You are trying to compile an executable, so a main function is expected. You should compile an object file by using the -c flag:

g++ -c myClass.cpp

While you are at it, I suggest adding warning flags -Wall -Wextra at the very least.

like image 39
juanchopanza Avatar answered Oct 19 '22 14:10

juanchopanza