What is the Microsoft Visual Studio equivalent to GCC ld option --whole-archive

亡梦爱人 提交于 2019-11-27 23:29:39

To my knowledge, there is no single option which reliably guarantees that. There are combinations of optimizing options which (silently) deactivate this, so no way... /INCLUDE works, but for that you need to extract and hardcode the mangled name of the symbol. You have two choices: (1) ensure, that all registrars are contained (included) in the translation unit containing main and enforce their usage. (2) Give up this 'idiom' and use explicit registration.

Caution: this answer is now almost 7 years old and the statements regarding the availability of options in the MSVC++ toolchain are outdated. Nevertheless I still recommend not to rely on registrar pattern and look at the alternatives. Please feel free to down vote because of this recommendation but I guess it's a bit unfair to down vote because the option was added to Microsoft linker in the meantime.

The version of Visual C++ in Visual Studio 2015 Update 2 includes a new flag to link.exe called /WHOLEARCHIVE, which has equivalent functionality to the --whole-archive option to ld. According to the flag documentation:

The /WHOLEARCHIVE option forces the linker to include every object file from either a specified static library, or if no library is specified, from all static libraries specified to the LINK command.

I believe about the closest equivalent would be /OPT:NOREF.

I use /INCLUDE: to force inclusion of unused symbols.

You can use with CMake like:

add_executable(hello ${SOURCE_FILES})
target_link_libraries(hello libA libB libC)     # Not need /wholearchive libC 
set_target_properties(hello PROPERTIES LINK_FLAGS "/WHOLEARCHIVE:libA /WHOLEARCHIVE:libB")

Note: /WHOLEARCHIVE only available Visual Studio 2015 Update 2+

I used another approach - rather than compiling everything to a .lib and then link that .lib to the executable, I link the executable directly against the .obj files.

In CMake, this can be made like this:

add_library(common OBJECT ${common_sources})
add_executable(executable1 "main1.cc" $<TARGET_OBJECTS:common>
add_executable(executable2 "main2.cc" $<TARGET_OBJECTS:common>

Changing any of the files in ${common_sources}) only recompiles their equivalent objects and relinks the executables, which provides the same benefits as if you linked things through intermediate .lib. At the same time, all the static constructors remain in place, which resolves the issue.

Note that this is only useful if you link things statically.

This approach was tested with gcc 5.2.0, MinGW-w64 5.2.0 and MSVC 15.

In the property page of the executable look at Common Properties/References/Use Library Dependency Inputs set that to true. That's pretty much the MS equivalent of --whole-archive in a nutshell.

Edit: However the library in question needs to be part of the solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!