这在实践中很少出现问题。
对于static
头文件中定义的函数和内联模板函数,无需担心:每个编译单元都有自己的副本(例如,在.a
库中可能已经有许多匿名副本)。这没关系,因为这些定义没有被导出,所以链接器不需要担心它们。
对于使用非静态链接声明的函数,是否有问题取决于链接.a
库的方式。
构建库时,通常不会在标准 C++ 库中进行链接。创建的库将包含对标准 C++ 库的未定义引用。这些必须在构建最终的可执行二进制文件之前解决。这通常在以默认方式链接最终二进制文件时自动完成(取决于编译器)。
There are times when people do link in the standard C++ library into a static library. If you're linking against multiple static libraries that each embed another library (like the standard C++ library), then expect trouble if there are any differences in those embedded libraries. Fortunately, this is a rare problem, at least with the gcc
toolchain. It's a more frequent problem with Microsoft's tools.
In some cases, a workaround is to make one or more conflicting static libraries into a dynamic library. This way each of these dynamic libraries can statically link its own copy of the problematic library. As long as the dynamic library doesn't export the symbols from the problematic library and there are no memory layout incompatibilities, there generally isn't any trouble.