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


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
Question

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?




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.




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.




I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.

  1. Let's say you have 5 cpp files, all you have to do is use the * instead of typing each cpp files name E.g g++ -c *.cpp -o myprogram.
  2. This will generate "myprogram"
  3. run the program ./myprogram

that's all!!

The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)

p.s Use this method only if you don't care about makefile.