c++ - header Using G++ to compile multiple .cpp and .h files



4 Answers

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

    g++ -c myclass.cpp
    g++ -c main.cpp
    g++ myclass.o main.o
    ./a.out
how to compile multiple c++ files in terminal

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?




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.




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).




I used to use a custom Makefile that compiled all the files in current directory, but I had to copy it in every directory I needed it, everytime.

So I created my own tool - Universal Compiler which made the process much easier when compile many files.




Related