Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: How to run a add_custom_command before everything else

Tags:

cmake

I have a custom command

add_custom_command(     OUTPUT config.h     PRE_BUILD     COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/mk_config_h.py ${CMAKE_CURRENT_BINARY_DIR}/config.h ) 

I'm trying to run it before everything else and I generate unix Makefiles.

However PRE_BUILD is only supported for VS2010 which means that config.h is build before linking.

how do I make a custom command before cmake starts compiling sources.

like image 601
Alexander Oh Avatar asked Apr 12 '13 13:04

Alexander Oh


People also ask

What does add_ custom_ command do?

add_custom_command adds a callable function that can have defined outputs (using the OUTPUT and BYPRODUCTS arguments). It can also have dependencies that will be run before the function is called.

What does Add_custom_target do in CMake?

Adds a target with the given name that executes the given commands. The target has no output file and is always considered out of date even if the commands try to create a file with the name of the target.


2 Answers

You should use add_custom_target instead and add_dependencies to make your normal target depend on it:

add_custom_target(     myCustomTarget     COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/mk_config_h.py ${CMAKE_CURRENT_BINARY_DIR}/config.h ) add_dependencies(myTarget myCustomTarget) 

This should ensure that the command is run before compiling the sources of myTarget.

like image 151
Simon Avatar answered Oct 03 '22 22:10

Simon


Usualy build systems which are based on makefiles do not need to mention headers as part of a target. Further more, adding headers to target is considered to be an antipattern. But generating a header is an exception from this rule.

http://voices.canonical.com/jussi.pakkanen/2013/03/26/a-list-of-common-cmake-antipatterns/

You should set your ${CMAKE_CURRENT_BINARY_DIR}/config.h as part of some other compilled target. For example:

set(PROGRAM1_SOURCES main_program1.cpp) set(PROGRAM1_HEADERS main_program1.h ${CMAKE_CURRENT_BINARY_DIR}/config.h) add_executable(program1 ${PROGRAM1_SOURCES} ${PROGRAM1_HEADERS}) 

So that, CMake will know which target actually needs the generated config.h and will be able to insert the generation commands into a right build steps.

Also, see an example at https://cmake.org/cmake-tutorial/#s5

like image 25
Piroxiljin Avatar answered Oct 03 '22 22:10

Piroxiljin