How to build object files only once with cmake?

In recent CMake versions, you can use an object library. It will mostly behave like any libraries but won't archive it into a static library:

add_library(my_cpps OBJECT a.cpp b.cpp c.cpp)

You can then "link" it to other targets:

add_library(my_lib1 d.cpp e.cpp f.cpp)
target_link_libraries(my_lib1 PUBLIC my_cpps)

add_library(my_lib2 f.cpp g.cpp h.cpp)
target_link_libraries(my_lib2 PUBLIC my_cpps)

No. This would be difficult to achieve since the source files could be compiled with different compiler options, post-build steps, etc.

What you can do is to put the object files into a static library and link with that instead:

add_library(mylib STATIC source1.c source2.c)
add_executable(myexe source3.c)
target_link_libraries(myexe mylib)

EDIT: of course, you can put it in a shared library as well.


Yes, in CMake 2.8.8 you can use an object library, which is a kind of virtual library that has the same organizational and dependency properties of a real static or shared library, but does not produce a file on disk. See CMake Tutorials: Object Library.

Tags:

Cmake