c++ - 如何强制 MSVC 链接未使用的静态库(相当于 GCCs --whole-archive 参数)

标签 c++ visual-c++ linker

<分区>

有一个静态库被主程序间接使用。因此没有遗漏引用,也没有链接静态库。

发布了同样的问题here对于海湾合作委员会。提议的解决方案也对我有用。但现在我需要用 MSVC 构建程序。所以我想我需要 GCC 的 --whole-archive 参数的等价物?

目前链接器调用是这样的:link.exe/nologo/out:program.exe staticLib.lib main.obj

有人可以帮我吗?

最佳答案

我最近在尝试将 googletest 与包含测试的库链接时遇到了同样的问题,并在他们的 primer 中发现了以下注释:

When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:

__declspec(dllexport) int PullInMyLibrary() { return 0; } 

If you put your tests in a static library (not DLL) then __declspec(dllexport) is not required. Now, in your main program, write a code that invokes that function:

      int PullInMyLibrary();
      static int dummy = PullInMyLibrary(); 

This will keep your tests referenced and will make them register themselves at startup.

In addition, if you define your tests in a static library, add /OPT:NOREFto your main program linker options.

虽然这可能不是有史以来最漂亮的解决方法,但这对我来说确实有效,我认为如果有更好的解决方法,他们会在入门手册中提到它。

关于c++ - 如何强制 MSVC 链接未使用的静态库(相当于 GCCs --whole-archive 参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29407552/

相关文章:

c++ - 用于 UDP 数据包接收的 Qt GUI

c++ - 如何确定返回为 void * 的指针的类型(Class)?

c++ - 将 VARIANT 转换为无符号字符数组

image - 如何在C++中加载24位Tiff图像

c - 与 gcc 链接时出错?

c++ - gcc 链接器找不到库

c++ - 如何通过引用从线程返回结果?

c++ - Eigen 3 - 切片 MatrixXd 以反转列顺序

c++ - 给定大小为 26 * 7 的图像是否有可能在 Mat 的每一行中包含 78 个单独的颜色值,而另一个可以包含 77 个?

Delphi链接包时会发生什么?