clinkerpreprocessor

Ambiguity in Functioning of preprocessor and linker


pls someone clear my doubt that during compilation process preprocessor replaces the declaration of predefined function but not the defination then why we did not get error during compilation that function not defined as function defination is added to code after compilation in linking phase??

Pls someone tell what is the actual functioning of preproceesor and linking?


Solution

  • This seems like a good time for you to learn about the concept of translation units.

    Summarized, a translation unit (or TU for short) is a single source file with all included header files. It's what the compiler actually sees, and it doesn't know anything about other translation units.

    So if there's a declaration of a function, the compiler will know about that, but if the definition (implementation) is in another TU then the compiler will not know about that. The compiler can generate a call to the function, but leave a kind of note in the object file that there's a reference to a function in another translation unit.

    This is where the linker comes in: It takes all translation units (object files) and libraries, and resolves references to functions in the different translation units.


    Header files themselves are never "compiled" on their own, they are always included in the source files. Basically the code of the header file is copy-pasted into the source file.

    So once the preprocessor is done, neither the compiler nor the linker knows anything about the header files. All they see are the single translation units.