Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 500
user1607549 Avatar asked Oct 15 '12 16:10

user1607549


2 Answers

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

like image 138
Alexey Avatar answered Sep 22 '22 10:09

Alexey


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).

like image 24
maxschlepzig Avatar answered Sep 19 '22 10:09

maxschlepzig