简体   繁体   中英

Can a C++ Static Library link to shared library?

Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible?

Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case?

I am using Microsoft Visual Studio 2003.

Static libraries are not linked. They are just a collection of object files (*.obj or *.o) that are archived together into a library file (kind of like a tar/zip file) to make it easier for the linker to find the symbols it needs.

A static lib can call functions that are not defined (but are only declared in a header file), as it is only compiled. Then when you link an exe or dll that uses the static lib you will have to link with another library that provides the called from the static lib but not defined in it.

If you want to the linker to automatically link other libraries Stephen's suggestion will work and is used by very reputable libraries like boost and stlport. To do this put the pragma in the main header file for the static library. You should include the static library and its dependants.

However IMO this feature is really meant for library writers, where the library is in the system library path so the linker will easily find it. Also in the case of boost and stlport they use this feature to support multiple version of the same libraries with options defined with #define s where different options require different versions of the library to be linked. This means that users are less likely to configure boost one way and link with a library configured another.

My preference for application code is to explicitly link the required parts.

链接器不会自动引入其他库,但您可以使用#pragma comment(lib,“static.lib”)通过将pragma添加到头文件来简化链接其他文件的过程。

Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible?

Yes for instance when you call windows functions from within your static lib they are normally from some dynamic library so there should be no difference.

Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case?

Having dependencies like this one could cause problems later, I would suggest that you instead dynamically load the libraries using LoadLibrary() , that way you don't need to keep track of such dependencies while compiling/linking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM