Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an object file needed to generate an executable file?

When we compile code, an object file is generated. From that object file, an executable file is generated in the linking process.

Why do we need an object file? What is the use of an object file? Can't it be possible that an executable file is generated directly? After all, we are using an executable file to run the program.

like image 627
shreyas_patel21 Avatar asked Dec 22 '12 08:12

shreyas_patel21


1 Answers

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

You can usually have your compiler output an executable "directly", the syntax will depend on the compiler. For instance with GCC:

gcc foo.c bar.c ...

will produce an executable and no intermediate object file will remain (but one will probably have been generated - and subsequently deleted).

Object files are used to make an incremental build. You compile each source file (or group of source files) to object files, then link all of them together in an executable. This allows you to only re-compile the source files that have changed since the last time you built, saving potentially a lot of time.
Or you could use the same object files to link different executables (re-use parts of your build to generate both an executable and a shared library for instance), again saving time and resources compared to compiling everything every time.

Object files aren't "needed" from a theoretical point of view. They're just very practical (and actually necessary technically with some (most?) toolchains, being the things the assembler knows how to produce and the linker knows how to link).

like image 131
Mat Avatar answered Sep 28 '22 02:09

Mat