前言:
這裡討論下純Linux環境下Gcc的使用, 兩者大致一樣, 但是還是有細微的差別, 請注意區分開
因為有了前面的簡單介紹, 所以這裡重點列舉幾個Sample, 通過Sample來分析下Linux-Gcc的編譯選項.
(因為我經常被這些東西搞糊塗, 所以表文於此, 希望新手少走點彎路. ^_^)
1. 根據Src檔案, 直接編譯成Exe檔案
gcc Sample.c SampleLib.c -o Sample.exe
2. 先編譯成Obj檔案, 然後連結成Exe檔案
gcc -c Sample.c -o Sample.o
gcc -c SampleLib.c -o SampleLib.o
gcc Sample.o SampleLib.o -o Sample.exe
或者使用LD進行串連
ld --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcc-lib/i386-redhat-linux/3.2.2/crtbegin.o /usr/lib/gcc-lib/i386-redhat-linux/3.2.2/crtend.o -L/usr/lib/gcc-lib/i386-redhat-linux/3.2.2 -L/usr/lib/ -lgcc -lgcc_eh -lc /usr/lib/crtn.o Sample.o SampleLib.o -o Sample.exe
選項參數的詳細說明:
//--eh-frame-hdr : Create .eh_frame_hdr section
//-m Emulation : set emulation : elf_i386
//-dynamic-linker xxx : link against shared library [xxx]
//crt1.o && crti.o : provide init-function
//crtn.o : provide clean-function
//crtbegin.o : for constructor support
//crtend.o : for destructor suport
3. 編譯成Obj檔案和SO檔案(動態連結程式庫), 然後連結成Exe檔案
gcc -c Sample.c -o Sample.o
gcc -shared SampleLib.c -o libSampleLib.so
gcc Sample.o -Wl,-L"./" -Wl,-R"./" -lSampleLib -o Sample.exe
詳細說明 :
//-lSampleLib : link the libSampleLib.so
//-Wl,-L"./" : when build, where to search the links.
//-Wl,-R"./" : when at runtime, where to search the links.
額外說明: 關於RunTime時候的SO檔案的尋找方式:
"Here's a brief primer on the way that this works on Solaris and Linux.
The search paths for libraries come from three sources:
the environment variable LD_LIBRARY_PATH (if set),
any rpath encoded in the binary (more on this later),
and the system default search paths.
They're searched in this order, and the first matching library found is used."
即首先尋找環境變數LD_LIBRARY_PATH (可以用export LD_LIBRARY_PATH=xxx來設定),
再尋找內部串連 (rpath, 即我們用-R選項指定的PATH),
再尋找系統設定PATH (Linux為:/etc/ld.so.conf檔案, 可以使用ldconfig配置)
4. 把[SampleLib.h]放到Src的上一級目錄, 然後按照3的方式來編譯產生Exe檔案
gcc -c Sample.c -o Sample.o
gcc -I"./../" -shared SampleLib.c -o libSampleLib.so
gcc Sample.o -Wl,-L"./" -Wl,-R"./" -lSampleLib -o Sample.exe
詳細說明:
//-I"./../" : when build, where to search the include-header-file.
參考資料: (重點推薦)
http://www.eyrie.org/~eagle/notes/rpath.html