tomshafer tomshafer - 1 year ago 98
C Question

Why Compile to an Object File First?

In the last year I've started programming in Fortran working at a research university. Most of my prior experience is in web languages like PHP or old ASP, so I'm a newbie to compile statements.

I have two different code I'm modifying.

One has an explicit statement creating .o files from modules (e.g. gfortran -c filea.f90) before creating the executable.

Another are creating the executable file directly (sometimes creating .mod files, but no .o files, e.g. gfortran -o executable filea.f90 fileb.f90 mainfile.f90).

  • Is there a reason (other than, maybe, Makefiles) that one method is preferred over the other?

Answer Source

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


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


  • There are some optimizations (like optimizing functions away) that the compiler can't perform and the linker don't care; 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 programmer of object file has to provide some kind of header for the use of others that will link with this object. (ie: in C you have to provide .h files). But it is good practice anyway.
  • in languages with text based includes like C or C++, if you change a file prototype you have to change it at two places. Once in header file, once in implementation file (if you use C++ you could also inline function implementation in header, but then it's not separate compilation any more)..