Meysam
Meysam

Reputation: 18117

CMake: How to execute a command before make install?

This is the way I install the config files:

file(GLOB ConfigFiles  ${CMAKE_CURRENT_SOURCE_DIR}/configs/*.xml
                            ${CMAKE_CURRENT_SOURCE_DIR}/configs/*.xsd
                            ${CMAKE_CURRENT_SOURCE_DIR}/configs/*.conf)

install(FILES ${ConfigFiles} DESTINATION ${INSTDIR})

But I need to convert one of the xml files before installing it. There is an executable that can do this job for me:

./Convertor a.xml a-converted.xml

How can I automatically convert the xml file before installing it? It should be a custom command or target that installing depends on it, I just don't know how to make the install command depend on it though. Any advice would be appreciated!

Upvotes: 2

Views: 7298

Answers (2)

ComicSansMS
ComicSansMS

Reputation: 54589

Take a look at the SCRIPT version of install:

The SCRIPT and CODE signature:

install([[SCRIPT <file>] [CODE <code>]] [...])

The SCRIPT form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The CODE form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string.

For example:

install(CODE "execute_process(COMMAND \"./Convertor a.xml a-converted.xml\")")
install(FILES a-converted.xml DESTINATION ${INSTDIR})

Be sure to checkout the entry for execute_process in the manual. Also be aware that macro expansion inside the CODE parameter can be a bit tricky to get right. Check the generated cmake_install.cmake in your build directory where the generated code will be placed.

Upvotes: 12

Alexis Wilke
Alexis Wilke

Reputation: 20725

I think that your specific case would work better if you were to use a custom command and target like so:

add_custom_command(
    OUTPUT ${CMAKE_BINARY_DIR}/a-converted.xml
    COMMAND ./Convertor a.xml a-converted.xml
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Convertor
)

add_custom_target(run ALL
    DEPENDS ${CMAKE_BINARY_DIR}/a-converted.xml
    COMMENT "Generating a-converted.xml" VERBATIM
)

install(
    FILES ${CMAKE_BINARY_DIR}/a-converted.xml
    DESTINATION ${INSTDIR}
)

Note: I don't have all the details, so the directories are probably not exactly what you'd want in your environment, although it's a good idea to generate files in the ${CMAKE_BINARY_DIR} area.

That way you can be sure that the file a-converted.xml is built at the time you want to install it. Especially, these two rules make sure that if you make changes to the original file (a.xml), it gets recompiled.

Upvotes: 2

Related Questions