How does the compilation/linking process work?

前端 未结 5 1284
灰色年华
灰色年华 2020-11-21 05:00

How does the compilation and linking process work?

(Note: This is meant to be an entry to Stack Overflow\'s C++ FAQ. If you want to critique the idea of

5条回答
  •  北海茫月
    2020-11-21 05:31

    GCC compiles a C/C++ program into executable in 4 steps.

    For example, gcc -o hello hello.c is carried out as follows:

    1. Pre-processing

    Preprocessing via the GNU C Preprocessor (cpp.exe), which includes the headers (#include) and expands the macros (#define).

    cpp hello.c > hello.i
    

    The resultant intermediate file "hello.i" contains the expanded source code.

    2. Compilation

    The compiler compiles the pre-processed source code into assembly code for a specific processor.

    gcc -S hello.i
    

    The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".

    3. Assembly

    The assembler (as.exe) converts the assembly code into machine code in the object file "hello.o".

    as -o hello.o hello.s
    

    4. Linker

    Finally, the linker (ld.exe) links the object code with the library code to produce an executable file "hello".

        ld -o hello hello.o ...libraries...
    

提交回复
热议问题