簡體   English   中英

在鏈接可執行文件之前找到 static 庫未解析的依賴項

[英]Find static library unresolved dependencies before linking executable

假設我們有 static 庫 mylib.a,其中包含已編譯的 cpp 文件。

文件 1.cpp:

int do_stuff();

int func_unres()
{
  int a = do_stuff();
  return a;
}

文件 2.cpp:

int do_other_stuff();

int func_res()
{
  int a = do_other_stuff();
  return a;
}

文件 3.cpp:

int do_other_stuff()
{
  return 42;
}

所以,正如我們在這里看到的,沒有文件包含do_stuff function 的定義。 圖書館以這種方式創建:

g++ -c file1.cpp -o file1.o

g++ -c file2.cpp -o file2.o

g++ -c file3.cpp -o file3.o

ar r mylib.a file1.o file2.o file3.o

現在我們嘗試用這個庫制作一些二進制文件。 簡單示例主文件:

#include <iostream>

int func_res();

int main()
{
  std::cout << func_res() << std::endl;
}

編譯:

g++ main.cpp mylib.a -o my_bin

一切正常。 現在考慮這樣的主文件的情況:

#include <iostream>

int func_unres();

int main()
{
  std::cout << func_unres() << std::endl;
}

在這種情況下,二進制文件不會鏈接,因為func_unres需要定義 function do_stuff

有沒有辦法找出 static 庫在將其與使用此類符號的可執行文件鏈接之前需要庫中沒有 object 文件包含的符號?

編輯:問題不是如何簡單地列出這些符號,而是要獲得一個 output 和 linker 之類的錯誤。 就像我使用它應該包含的所有符號將這個庫與可執行文件鏈接一樣。

It seems that as pointed in comments and in How to force gcc to link an unused static library , linker option --whole --whole-archive is enough to force resolve all symbols and output linker error for all unresolved symbols in static library. 所以參考問題示例,以這種方式編譯和鏈接第一個主文件,它不引用未定義的符號,無論如何都會 output linker 錯誤:

g++ main.cpp -Wl,--whole-archive mylib.a -Wl,--no-whole-archive

盡管 main 不使用func_unres ,但鏈接失敗:

mylib.a(file1.o): 在 function func_unres(): file1.cpp:(.text+0x9): 未定義對 do_stuff() 的引用

使用第二個選項--no-whole-archive ,因此不會像這樣強制解析所需庫符號的 rest。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM