C Compiler – Role of Linking, Object Files, and Executables

assemblyccompiler

  1. For a C or assembly program that does not require any other library, will linking
    be necessary? In other words, will conversion from C to Assembly and/or from Assembly to an object file be enough without being followed by linking?

    If linking is still needed, what
    will it do, given that there is just one object file which doesn't
    need a library to link to?

  2. Relatedly, how different are object files and executable files,
    given that in Linux, both have file format ELF?

    Are object files those ELF files that are not runnable?

    Are there some executable files that can be linked to object files?
    If yes, does it mean dynamical linking of executables to shared
    libraries?

Best Answer

First of all, it's really hard for any non-trivial program to 'not require any other library'. Remember that glibc and the startup code calling main() are libraries too.

But yes, even in this case you need the linker, just because the compiler/assembler typically don't handle ELF format (or any executable format). Precisely because usually you'll have to link with some libraries, so why should it bother to compile to ELF? It's better to focus on linkable-code formats and leave the executable formats to the linker.

PS: I forgot that .so is also a variant of ELF. But it still doesn't change the fact that it's a different subformat and the executable details are just not included in most compiler/assembers.

Yes, it's quite possible for a single tool to compile directly to executable, but that just means that it includes both the compiler and the linker in a single command. Why would it consider the (very) special case when you won't add any other code? It's far more logical to do it in the linker, after all you'll need it in %99.9 cases.