Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake add_custom_command not being run

Tags:

cmake

I'm trying to use add_custom_command to generate a file during the build. The command never seemed to be run, so I made this test file.

cmake_minimum_required( VERSION 2.6 )  add_custom_command(   OUTPUT hello.txt   COMMAND touch hello.txt   DEPENDS hello.txt ) 

I tried running:

cmake .   make 

And hello.txt was not generated. What have I done wrong?

like image 325
Jonathan Sternberg Avatar asked May 30 '10 00:05

Jonathan Sternberg


1 Answers

The add_custom_target(run ALL ... solution will work for simple cases when you only have one target you're building, but breaks down when you have multiple top level targets, e.g. app and tests.

I ran into this same problem when I was trying to package up some test data files into an object file so my unit tests wouldn't depend on anything external. I solved it using add_custom_command and some additional dependency magic with set_property.

add_custom_command(   OUTPUT testData.cpp   COMMAND reswrap    ARGS    testData.src > testData.cpp   DEPENDS testData.src  ) set_property(SOURCE unit-tests.cpp APPEND PROPERTY OBJECT_DEPENDS testData.cpp)  add_executable(app main.cpp) add_executable(tests unit-tests.cpp) 

So now testData.cpp will generated before unit-tests.cpp is compiled, and any time testData.src changes. If the command you're calling is really slow you get the added bonus that when you build just the app target you won't have to wait around for that command (which only the tests executable needs) to finish.

It's not shown above, but careful application of ${PROJECT_BINARY_DIR}, ${PROJECT_SOURCE_DIR} and include_directories() will keep your source tree clean of generated files.

like image 144
Rian Sanderson Avatar answered Sep 20 '22 08:09

Rian Sanderson