Search code examples
c++compiler-constructionlinkerobject-files

Why are many object files linked instead of one large object file?


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?


Solution

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