C header files and compilation/linking

后端 未结 5 1068
迷失自我
迷失自我 2020-12-04 18:06

I know that header files have forward declarations of various functions, structs, etc. that are used in the .c file that \'calls\' the #include, ri

5条回答
  •  粉色の甜心
    2020-12-04 18:47

    Uchia Itachi gave the answer. It's the linker.

    Using GNU C compiler gcc you would compile a one-file program like

    gcc hello.c -o hello # generating the executable hello
    

    But compiling the two (or more) file program as described in your example, you would have to do the following:

    gcc -c func.c # generates the object file func.o
    gcc -c main.c # generates the object file main.o
    gcc func.o main.o -o main # generates the executable main
    

    Each object file has external symbols (you may think of it as public members). Functions are by default external while (global) variables are by default internal. You could change this behavior by defining

    static int func(int i) { # static linkage
        return ++i ;
    }
    

    or

    /* global variable accessible from other modules (object files) */
    extern int global_variable = 10; 
    

    When encountering a call to a function, not defined in the main module, the linker searches all the object files (and libraries) provided as input for the module where the called function is defined. By default you probably have some libraries linked to your program, that's how you can use printf, it's already compiled into a library.

    If you are really interested, try some assembly programming. These names are the equivalent of labels in assembly code.

提交回复
热议问题