How do you merge multiple static linked libraries

2019-05-23 16:11发布

问题:

How do you merge multiple static linked libraries into a single dll given each static lib defines exported functionality (vc++ 2008)?.

In a multi project layout existing out of a single dll project and multiple sub projects that are linked in statically (in the dll project). Despite being marked as __declspec(export) some of the symbols in the sub-projects (.lib) refuse to have their symbols exported in the final dll.

Generating a .def file and marking the symbols explicitly for exportation could solve this problem. However identifying which of the symbols are marked as __declspec( export ) proofs a problem. Due large number of exported classes/function and primarily name mangling maintaining a list by hand is a unfordable process thus generating the list of symbols, that were marked for export, would be the only viable option.

Is there an utility or compiler directive could do this?

回答1:

Use a DEF file.

Always use a DEF file.

Never fail to use a DEF file.

Just accept that a DEF file is the thing to use.

Stop using __declspec(dllexport), and use a dang-dratted def file already.

Also don't export classes. Export those class members which need to be exported only. And use a DEF file to do it.

Seriously, if you export classes without a DEF file, the function names will be several times longer than the actual program data. You should to use ordinals for exporting C++ member functions.



回答2:

After bit trial and error I found that using the lib /def command can be utilized to generate an import library and export file. It appears that the export file contains all symbols that are marked with __declspec(dllexport). Subsequently the .exp file can be inspected with dumpbin and used as a reference to generate a module definition file.



回答3:

Starting with Visual Studio 2015 Update 2 there is a new way of doing this, by using the linker option /WHOLEARCHIVE

It's documented here

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. To specify the /WHOLEARCHIVE option for multiple libraries, you can use more than one /WHOLEARCHIVE switch on the linker command line. By default, the linker includes object files in the linked output only if they export symbols referenced by other object files in the executable. The /WHOLEARCHIVE option makes the linker treat all object files archived in a static library as if they were specified individually on the linker command line.