ccompilationlinkerincludeobject-code

About C compilation process and the linking of libraries


Are C libraries linked with object code or first with source code so only later with object code? I mean, look at the image found at Cardiff School of Computer Science & Informatics's website :

Compile process

It's "strange" that after generating object-code the libraries are being linked. I mean, we use the source code while putting the includes!

So.. How this actually works? Thanks!


Solution

  • That diagram is correct.

    When you #include a header, it essentially copies that header into your file. A header is a list of types and function declarations and constants, etc., but doesn't contain any actual code (C++ and inline functions notwithstanding).

    Let's have an example: library.h

    int foo(int num);
    

    library.c

    int foo(int num)
    {
        return num * 2;
    }
    

    yourcode.c

    #include <stdio.h>
    #include "library.h"
    int main(void)
    {
        printf("%d\n", foo(100));
        return 0;
    }
    

    When you #include library.h, you get the declaration of foo(). The compiler, at this point, knows nothing else about foo() or what it does. The compiler can freely insert calls to foo() despite this. The linker, seeing a call to foo() in youcode.c, and seeing the code in library.c, knows that any calls to foo() should go to that code.

    In other words, the compiler tells the linker what function to call, and the linker (given all the object code) knows where that function actually is.

    (Thanks to Fiddling Bits for corrections.)