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

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.


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.

Tags:

C++

G++