0

Why is it that compiled programming languages (C++ for example) are set up to create many object files that are linked together as opposed one large object being created?

For example (written in C++, could apply to any compiled language), consider two files in a project main.cpp and auxiliary.cpp. What is the difference between main.cpp and auxiliary.cpp being compiled to main.o and auxiliary.o and then linked to main.exe, and main.cpp with a #include auxiliary.cpp being compiled to only main.o and linked to main.exe? To my knowledge, these would at least superficially produce the same result.

I see the necessity for multiple objects in the case of multi-language projects, but not otherwise. Does multiple objects somehow give the linker more flexibility in creating an executable?

Brendon Boldt
  • 235
  • 2
  • 11
  • How would you find anything in a single cpp file that was several hundred thousand lines long containing thousands of classes? Also when I change 1 line I would not want to wait 1 hour to compile. – drescherjm Jun 19 '14 at 02:02
  • Using the `#include` preprocessor command, the source would be in many files to the user, but appear as one file to the compiler. – Brendon Boldt Jun 19 '14 at 02:04
  • That would suffer from unnecessarily long compile times. – drescherjm Jun 19 '14 at 02:05

3 Answers3

6

Separate compilation units like this make compiling faster. If you make a change in auxilliary.cpp, the compiler only needs to recreate auxilliary.o rather than recompiling everything. This becomes especially important the larger the project is.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

I can answer this with a rhetorical question: Why do you write many functions instead of one big one?

The same logic applies at the link level.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

If you want one big binary you just need to build a static library, but that is not the object code from one translation unit, but from many.

Now consider whether what you are asking really makes sense: If it was to create a single .o file, it would have to merge the results of the compilation of each cpp into that binary as it proceeded building, effectively paying the cost of linking multiple times. Furthermore, a change to one translation unit would require that the compiler figured out which of the symbols in the large object file came from the original version of this translation unit, remove those from the object and add the new ones after rebuilding.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489