Why is an object file necessary to create an executable file?

When compiling the code, an object file is created. An executable file is created from this object file during the build process.

Why do we need an object file? What is the use of an object file? Is it not possible to create an executable file directly? In the end, we use the executable to run the program.

+7
source share
1 answer

Object files are what the linker uses to create complete executables (or libraries).

Usually you can get your compiler as an executable file "directly", the syntax will depend on the compiler. For example, using GCC:

gcc foo.c bar.c ... 

will create an executable file, and no intermediate object file will remain (but it will probably be generated and subsequently deleted).

Object files are used to create an incremental assembly. You compile each source file (or group of source files) into object files, and then combine all of them together in an executable file. This allows you only to recompile the source files that have been modified since the last creation, which saves from time to time.
Or you can use the same object files to link different executables (reusing parts of your assembly to generate both an executable and a shared library), again saving time and resources compared to compiling everything every time.

Object files are not "necessary" from a theoretical point of view. They are just very practical (and actually technically necessary with some (most?) Toolchains, being that the assembler knows how to produce and the linker knows how to put together).

+11
source

All Articles