C++ 静态库可以链接到共享库吗?

C++ 静态库可以链接到共享库吗?

问题描述:

假设我有一个静态 C++ 库,static.lib,我想从 C++ 共享库调用一些函数,比如 shared.lib.可能吗?

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?

现在假设我有另一个共享库,比如 shared2.lib,它链接到 static.lib 但不链接到 shared.lib.在这种情况下,链接器是否会自动将 shared2.lib 链接到 shared.lib?

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?

我使用的是 Microsoft Visual Studio 2003.

I am using Microsoft Visual Studio 2003.

未链接静态库.它们只是一组目标文件(*.obj 或 *.o),它们一起归档到一个库文件(有点像 tar/zip 文件)中,以便链接器更容易找到它需要的符号.

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.

静态库可以调用未定义(但仅在头文件中声明)的函数,因为它仅被编译.然后,当您链接使用静态库的 exe 或 dll 时,您将必须链接另一个库,该库提供从静态库调用但未在其中定义的库.

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.

如果您希望链接器自动链接其他库,Stephen 的建议将起作用,并且被非常有名的库使用,例如 boost 和 stlport.为此,将编译指示放在静态库的主头文件中.您应该包括静态库及其依赖项.

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.

然而,IMO 这个特性真正适用于库编写者,库位于系统库路径中,因此链接器很容易找到它.同样在 boost 和 stlport 的情况下,他们使用此功能来支持相同库的多个版本,其中使用 #define 定义的选项,其中不同的选项需要链接不同版本的库.这意味着用户不太可能以一种方式配置 boost 并链接到另一种配置的库.

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 #defines 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.