gcc 查看 引用頭文件的位置 , 庫的 搜索路徑 和 最終路徑

場景 一: 查找頭文件路徑.

代碼 使用了 msgpack庫,但makefile 沒有指定 msgpack的頭文件所在位置,也可以編譯通過。


可以得出 一定是在系統的某個位置 安裝了 msgpack,並且被找到。


但具體頭文件在哪個位置呢?


從網上 搜到 看到 都是 gcc/g++ 頭文件的 搜索路徑,-I指定頭文件的搜索路徑。 知道了搜索路徑,那我 需要 遍歷 搜索路徑上的每個目錄 去查找, 這樣比較費時, 但也是最容易想到的。


但可以通過 gcc 編譯程序的 過程,讓 gcc 自己列出所在位置.


gcc 由源碼到可執行二進制程序包含了:預處理,編譯,彙編,鏈接,四個階段;其對應gcc -E -S -c ,鏈接階段沒有特殊參數表示。


先說下gcc -o,這裏o代表 output,即指定輸出文件。

1.預處理階段:gcc -E test.c -o test.i,

-E參數指定處理到預處理階段停止,並輸出預處理結果,這裏指定輸出文件-o 是因爲指定的話會直接輸出到標準輸出,

2.編譯階段:gcc -S test.i -o test.s

這個階段會把test.s 編譯成 彙編代碼

3.彙編階段:gcc -c test.s test.o

這個階段,把彙編代碼,彙編成 二進制代碼

4.鏈接階段:gcc test.o -o test

和其他庫一起 鏈接生成 可執行文件 test



可以利用預處理階段 找到 xx.h


  1. make, 讓makefile 生成  gcc 指令,因爲可能包含了其他的 庫 頭文件,

  2. gcc -E test.c |grep xx.h


場景二: 查找庫的 搜索路徑和 最終位置

  1 #include "expat.h"
  2 
  3 int main()
  4 {
  5 }

gcc -c my.c -o my.o

ld --verbose -o my my.o -lexpat --entry main

輸出

attempt to open my.o succeeded
my.o
attempt to open /usr/x86_64-redhat-linux/lib64/libexpat.so failed
attempt to open /usr/x86_64-redhat-linux/lib64/libexpat.a failed
attempt to open /usr/local/lib64/libexpat.so failed
attempt to open /usr/local/lib64/libexpat.a failed
attempt to open /lib64/libexpat.so failed
attempt to open /lib64/libexpat.a failed
attempt to open /usr/lib64/libexpat.so failed
attempt to open /usr/lib64/libexpat.a failed
attempt to open /usr/x86_64-redhat-linux/lib/libexpat.so failed
attempt to open /usr/x86_64-redhat-linux/lib/libexpat.a failed
attempt to open /usr/lib64/libexpat.so failed
attempt to open /usr/lib64/libexpat.a failed
attempt to open /usr/local/lib/libexpat.so succeeded
-lexpat (/usr/local/lib/libexpat.so)
libc.so.6 needed by /usr/local/lib/libexpat.so
found libc.so.6 at /lib64/libc.so.6
ld-linux-x86-64.so.2 needed by /lib64/libc.so.6
found ld-linux-x86-64.so.2 at /lib64/ld-linux-x86-64.so.2

man ld

--verbose Display the version number for ld and list the linker emulations supported.  Display which input files can and cannot be opened.  Display the linker script being used by the linker.


如果有很多未定義的符號,爲了不影響 查看庫的搜索路徑,

--unresolved-symbols=ignore-all

ignore-all Do not report any unresolved symbols.



可以用 鏈接階段查看 庫的 搜索路徑

ld --verbose --unresolved-symbols=ignore-all  -o my my.o -lexpat --entry=main


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章