星期三, 3月 15, 2017

[ GCC ] Compiler 流程 (一) GCC使用方法


gcc不是個編譯器,他是個compiler driver,
當你呼叫gcc時,他會調用preprocessor,compiler,assembler和 linker。


1. preprocessor
/ # gcc -E compile.c -o compile.i

2. compiler
/ # gcc -S compile.i -o compile .s

3. assembler (as)
/ # as compile.s -o compile.o

4. linker (ld)
/ # ld *.o

SourceCode


(一) Preprocess
這步驟主要是展開程式碼,像是macro,
這時會把include的 .h 檔也展開,
像是:
int printf(const char* fmt, ...);
讓主程式可以認到真的有printf這個function name,
然後最後輸出就看不到#include這個字眼了。

(二) Compiler
這個compiler不是一般編譯的那個compiler,
他編譯出相對應的組合語言。
這時還不知printf的位址,所以會先寫上printf這字眼。

(三) Assembler
這時會把編譯好的組合語言,再轉成機械碼(machine code)。
但這時也還不知printf的位址。

(四) Linker
這時會把需要用到的 .o 或 library檔做連結,
那就可以知道printf的位址了。


gcc是從GCC的source code compiler出來的,
所以需要些什麼library就需要在compiler時就加參數進去。
用"gcc -v"可以查看哪些參數有被加進去。

vodka@swtest6 Compile (git:master) $ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 4.7.3-4' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --with-system-zlib --enable-objc-gc --with-cloog --enable-cloog-backend=ppl --disable-cloog-version-check --disable-ppl-version-check --enable-multiarch --with-arch-32=i586 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.7.3 (Debian 4.7.3-4)


Ref
Ref 2
Ref 3

沒有留言: