[C++] Using G++ to compile multiple .cpp and .h files


To compile separately without linking you need to add -c option:

    g++ -c myclass.cpp
    g++ -c main.cpp
    g++ myclass.o main.o

I've just inherited some C++ code which was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files which contain classes and their function definitions.

Until now the program was compiled using the command g++ main.cpp. Now that I've seperated the classes to .h and .cpp files do I need to use a makefile or can I still use the g++ main.cpp command?

Though previous posters covered your particular error, you can get 'Undefined reference' linker errors when attempting to compile C code with g++, if you don't tell the compiler to use C linkage.

For example you should do this in your C header files:

extern "C" {


void myfunc(int param);



To make 'myfunc' available in C++ programs.

If you still also want to use this from C, wrap the extern "C" { and } in #ifdef __cplusplus preprocessor conditionals, like

#ifdef __cplusplus
extern "C" {

This way, the extern block will just be “skipped” when using a C compiler.

Problems compiling windows c++ project on g++ 5

When you are compiling from command line, you need to make sure you include all object files (.o) when you link the executable.

Obviously, it is hard to control this manually, this is why people invented various sorts of Makefiles to do this for them. You can research this topic. To help your immediate problem, just make sure you have all your cpp files listed in your command line for compilation. Something like

g++ myProject.cpp Statistics.cpp ... <flags>  -o <executable>

C++ makefile on Linux with Multiple *.cpp files

you'll need to compile all .cpp files that you use (i assume they are not included somewhere). That way the compiler will know that file1.cpp and main.cpp are used together. Also I would suggest using g++ instead of gcc, because g++ is the specific c++ compiler while gcc supports C and C++.

Try using:

g++ -g -Wall -o main main.cpp file1.cpp

Also I would recommend to use Makefile variables like this:

SOURCES = main.cpp file1.cpp
g++ -g -Wall -o main $(SOURCES)

Hope this helps :)