tags:

views:

351

answers:

1

I have a CMakeLists.txt file that looks like this:

add_executable(exec1 exec1.c source1.c source2.c source3.c)
add_executable(exec2 exec2.c source1.c source2.c source3.c)
add_executable(exec3 exec3.c source1.c source2.c source3.c)

The source1.o source2.o source3.o files take a really long time to build, and since they are common to all the executables, I want each of them to be built only once. The current behavior for cmake, however, is to rebuild them for each exec target separately, which is an unnecessary duplication of effort.

Is there a way to tell cmake to build object files only once?

+4  A: 

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.

JesperE
Take care with that approach. Shared libraries may be friendlier if there are lots of exes involved http://blog.flameeyes.eu/2008/01/21/what-to-do-with-shared-code
rq
Yes, of course. I think I just assumed that the OP wanted the code duplicated in each of the executables.
JesperE