Home > Software design >  Why do we need linkers if we have preprocessors?
Why do we need linkers if we have preprocessors?

Time:02-18

I know that a preprocessor replaces every preprocessor directive with the specified text in the preprocessing step. Then, if we have a function included in a library and we include that library and call that function, everything should work even without the linking step? Then, why do we need a linker?

CodePudding user response:

Preprocessing happens first:

Broadly speaking, it only replaces preprocessor ("#") symbols with whatever you've defined them to be.


Compilation happens second:

This step is executed separately for each source file, which means that it does not include the resolution of any function-call to a function which resides in a different source file (see below what 'resolution' means).

The result of this step is a set of object (compiled source code) files, one per each source file.


Linkage happens third:

This step is executed on the set of object files generated in the previous step.

At this point, each call from one object file to a function which resides in another object file, can be resolved, i.e., translated to a jump to the address of that function within the executable image.

The result of this step is either an executable file (if you've implemented the main entry point), or a library file (if you haven't).


Again - all of the above is a Very Broadly Speaking kind of description.

CodePudding user response:

Your question is a bit fuzzy ... Linking is a mandatory step in compilation. The compiler generate an object file from every source file (excepted headers) in your project and the linker will stitches them into a single executable or shared library. Even without including a library, you need a linker. Read the Wikipedia article at https://en.wikipedia.org/wiki/Linker_(computing) .

  • Related