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";
}
};
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With