繁体   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