Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling multiple .cpp and .h files using g++. Am I doing it right?

Lets say I have these files: main.cpp, ClassA.cpp, ClassA.h, ClassB.cpp, ClassB.h

  • The main has #include "ClassA.h" and #include "ClassB.h" and each .cpp file includes its respective .h file. Is this correct?

Now I am compiling using g++ *.cpp after which I get an executable a.exe (Windows)

  • And my question is that is this the right way? And lets say if I only make changes in one file (cpp or h)will this command also recompile the unchanged files(because I see no new files in the folder except a.exe)? Please explain. Also how do I prevent that?

P.S I am not familiar with make and do not want to use that either so please do not refer to that in the answers and I read Using G++ to compile multiple .cpp and .h files but I need more explanation regarding my questions.

like image 399
pizzaEatingGuy Avatar asked Nov 08 '14 06:11

pizzaEatingGuy


2 Answers

If you want to do it manually, you can compile all your .cpp files into object files

g++ -c *.cpp

and link all the object files

g++ *.o -o a.out

If ClassA.cpp is changed, you can just recompile ClassA.cpp

g++ -c ClassA.cpp

and link them all again

g++ *.o -o a.out

At least, you do not need to recompile the unchanged .cpp files.

like image 160
Peter Li Avatar answered Sep 25 '22 07:09

Peter Li


And my question is that is this the right way?

It will be better to create a makefile and use make to build your target.

And lets say if I only make changes in one file (cpp or h)will this command also recompile the unchanged files(because I see no new files in the folder except a.exe)?

Yes.

Please explain. Also how do I prevent that?

Using make. make will help keep track of dependencies and compile files that need to be compiled, or in general build targets that are out of date.

like image 45
R Sahu Avatar answered Sep 21 '22 07:09

R Sahu