CMake - 将多个库合并为一个(CMake - combine multiple libraries into one)

假设我有可执行文件A,B,C,并且我有外部库X,Y,Z

SET(EXTERNAL_LIB X Y Z) TARGET_LINK_LIBRARIES(A, ${EXTERNAL_LIB}) TARGET_LINK_LIBRARIES(B, ${EXTERNAL_LIB}) TARGET_LINK_LIBRARIES(C, ${EXTERNAL_LIB})

但是,如果我将其可视化(使用cmake --graphviz选项,我会得到一个复杂的二分图,其中每个可执行文件A,B和C的边到每个库X,Y和Z.

我想知道是否有办法将所有库合并为一个。

Let's say I have executables A, B, C, and I have external libraries X, Y, Z

SET(EXTERNAL_LIB X Y Z) TARGET_LINK_LIBRARIES(A, ${EXTERNAL_LIB}) TARGET_LINK_LIBRARIES(B, ${EXTERNAL_LIB}) TARGET_LINK_LIBRARIES(C, ${EXTERNAL_LIB})

However, if I visualize this (using cmake --graphviz option, I get a complex bipartite graph with edges from each of the executables A, B, and C to each of the libraries X, Y, and Z.

I was wondering if there's a way to combine all the libraries into one.

最满意答案

所有这些都取决于您的平台,编译器和库的类型:

如果你可以自己构建X,Y,Z:创建一个新的项目XYZ ,从X,Y和Z的聚合源文件构建。但我想如果这是可能的,你就不会问SO了。

如果你不能重建lib并且它们被构建为共享库(dll / so),那你就不走运了。 您可以尝试编写一个包装器库,它隐藏X,Y和Z的所有内部,并将由应用程序A,B和C使用。

如果将它们构建为静态库,请查看此SO问题 。 因为静态库不仅仅是目标文件的存档,您可以从每个lib中提取目标代码并将它们与ar重新组合。

但你为什么要这样? 假设你得到第四个应用程序D,它只依赖于X.那么你无论如何都需要单独的库Y(除非你更愿意不必要地链接所有的库)。

All of this depends a bit on your platform, compiler and the type of libraries:

In case, you can build X, Y, Z yourself: Create a new project XYZ, built from the aggregated source files of X, Y and Z. But I guess if this was possible, you would not have asked on SO.

If you can not rebuild the libs and they were built as a shared libraryy (dll/so), you are out of luck. You could try to write a wrapper library, which hides all the internals of X, Y and Z and which will be used by applications A, B and C.

If they were build as static libs, take a look at this SO question. Because a static lib is not much more than an archive of object files, you may be able to extract the object code from each lib and recombine them with ar.

But why would you? Suppose you get a fourth application D, which only depends on X. Then you would need the separate library Y anyway (unless you prefer to unnecessarily link with all libs).

更多推荐