Why Compile to an Object File First?

Compiling to object files first is called separate compilation. There are many advantages and a few drawbacks.

Advantages:

  • easy to transform object files (.o) to libraries and link to them later
  • many people can work on different source files at the same time
  • faster compiling (you don’t compile the same files again and again when the source hasn’t changed)
  • object files can be made from different language sources and linked together at some later time. To do that, the object files just have to use the same format and compatible calling conventions.
  • separate compilation enables distribution of system wide libraries (either OS libraries, language standard libraries or third party libraries) either static or shared.

Drawbacks:

  • There are some optimizations (like optimizing functions away) that the compiler cannot perform, and the linker does not care about; however, many compilers now include the option to perform “link time optimization”, which largely negates this drawback. But this is still an issue for system libraries and third party libraries, especially for shared libraries (impossible to optimize away parts of a component that may change at each run, however other techniques like JIT compilation may mitigate this).
  • in some languages, the programmer has to provide some kind of header for the use of others that will link with this object. For example in C you have to provide .h files to go with your object files. But it is good practice anyway.
  • in languages with text based includes like C or C++, if you change a function prototype, you have to change it in two places. Once in header file, once in the implementation file.

Leave a Comment