views:

79

answers:

4

Hi,

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?

+2  A: 

You can still use g++ directly if you want:

g++ f1.cpp f2.cpp main.cpp

where f1.cpp and f2.cpp are the files with the functions in them. For details of how to use make to do the build, see the excellent GNU make documentation.

anon
+2  A: 

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

gauteh
+1  A: 

list all the other cpp files after main.cpp.

ie

g++ main.cpp other.cpp etc.cpp

and so on.

Or you can compile them all individually. You then link all the resulting ".o" files together.

Goz
You can even do `g++ *.cpp -o output`
rubenvb
+1  A: 

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?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make) it should suffice to write that:

# "all" is name of the default target, running "make" without params would use it
all: executable1

# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)

# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

Dummy00001