-1

I am studying OOP with c++ and using g++ compiler. I was wondering, when implementing separate compilation, what is the point of compiling to object files and then linking everything into an executable, instead of just using g++ to compile and link everything directly? What are the pros/cons of each process?

For example:

g++ -c main.cpp -o main.o
g++ -c func1.cpp -o func1.o
g++ -c func2.cpp -o func2.o

g++ -o test.exe main.o func1.o func2.o 

OR simply

g++ main.cpp func1.cpp func2.cpp -o test.exe

they do the same thing it seems, so what is the point of both processes? (I apologize if there are any mistakes that make the question less clear, thank you for your time)

DevSolar
  • 67,862
  • 21
  • 134
  • 209
Shivam
  • 211
  • 1
  • 13
  • 1
    It improves compilation speed. If you change one, everything else will need to be recompiled in the latter approach. In the first, only affected object files will need to get overwritten and linker will need to relink. – Incomputable Mar 20 '18 at 07:59
  • Note that your first example didn't work that way; you need to make *separate* calls per translation unit. (Hence my edit, which makes the example match your intentions.) And seconding previous commenters. I have a compilation unit in my code that takes close to a minute to compile. With the second way of compiling, I'd have to wait that minute *every time* I compile; with the first way, I have to wait that minute only when I actually modified that specific translation unit. – DevSolar Mar 20 '18 at 08:06

1 Answers1

0

Compiling to separate object files allows incremental compilation of only the cpp files that have changed. As hardly anybody invokes the compiler directly the extra effort involved is minimal (if you haven't already look into a build system like make, cmake etc.).

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60