Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: execute a macro/function as the command of add_custom_command

I'm using an external library which provides a CMake function for automatic code generation, to be used in my CMakeLists. The problem is that whenever I modify a CMakeLists then the function is run again, triggering the recompilation of the newly generated but unchanged sources. I'd need something like add_custom_command with the possibility to specify the CMake function as COMMAND instead of an executable, so that the function is run only if the automatically generated files are not already present. Is this feasible? If not, does it exist another way to obtain the same result? Thanks.

like image 522
Nicola Mori Avatar asked Jan 14 '15 15:01

Nicola Mori


People also ask

What would happen if you execute the file add_custom_command?

The command becomes part of the target and will only execute when the target itself is built. If the target is already built, the command will not execute. This defines a new command that will be associated with building the specified <target> .

What is add_custom_command?

The add_custom_command() documentation says "This defines a command to generate specified OUTPUT file(s). A target created in the same directory (CMakeLists. txt file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time."

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

Take a look to this SO post.

You can call your function in a separate CMake script, call this script with add_custom_target and cmake -P then add a dependency to your binary :

add_custom_target(run_script COMMAND ${CMAKE_COMMAND} -P separate_script.cmake)
add_executable(your_binary ...)
# or add_library(your_binary ...)
add_dependencies(your_binary run_script)
like image 112
cromod Avatar answered Nov 17 '22 02:11

cromod


Is there a way to pass a parameter to the separate_script.cmake?

You can use the cmake variables to pass values when you call the script e.g.

"COMMAND ${CMAKE_COMMAND} -DPARAM=value -P separate_script.cmake" 
like image 6
Karoly Molnar Avatar answered Nov 17 '22 02:11

Karoly Molnar