CMake: How can I build a shared and a static library without recompiling the sources twice

心已入冬 提交于 2019-12-08 15:07:52

问题


I want to build both a static and shared version of the same library as described Is it possible to get CMake to build both a static and shared version of the same library?

However, the sources are compiled twice, one for each version which is not necessary. Is there any way to avoid this?

Currently I have:

add_library(${LIB} SHARED ${${LIB}_srcs})

add_library(${LIB}_static STATIC ${${LIB}_srcs})

What do I need to change in order to only need to compile once? FYI. I have the same compiler flags and defines.


回答1:


It's unfeasible and not recommended to create the shared/static library version from the same set of object files - at least on many platforms.

Object files linked into a shared library must be compiled as position independent code (-fpic/-FPIC on Linux/Solaris etc.) - whereas your executable and static libraries (usually) doesn't contain position independent code. On the other hand, shared libraries trade off sharing code pages with runtime overhead due to indirections. Since those indirections are unnecessary for static libraries and binaries, position independent code provides only disadvantages with thoses. Thus, if you want to create both a shared and a static library version you need to create two different sets of object files (one which is position independent and one which is the opposite).




回答2:


Since CMake 2.8.8 you can use Object Library: CMake: reuse object files built for a lib into another lib target.

See also http://www.cmake.org/Wiki/CMake/Tutorials/Object_Library



来源:https://stackoverflow.com/questions/12899582/cmake-how-can-i-build-a-shared-and-a-static-library-without-recompiling-the-sou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!