Custom target cmake dependencies

I am using a python script (gen_instantiations.py) to create a cpp file (autogen_instantiations.cpp) that is included in another cpp file (foo.cpp) So I want CMake to regenerate this file when foo.hpp or gen_instantiations.py changes. Following the instructions from the CMake FAQ, here's what I did

add_custom_command(
  COMMAND "./gen_instantiations.py" 
  OUTPUT "autogen_instantiations.cpp"
  WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" 
  DEPENDS gen_instantiations.py foo.hpp
)
add_custom_target(instantiations ALL DEPENDS autogen_instantiations.cpp)

add_library(foo
   foo.cpp  
 )
 add_dependencies(foo instantiations)

      

But this run runs the script every time. What am I doing wrong?

+3


source to share


2 answers


the best approach is not #include

generated autogen_instantiations.cpp

, but adding it to the library foo

as another source file, so cmake could see what foo

depends on it and call your generator if smth has changed



set(GENERATED_SOURCES autogen_instantiations.cpp)
add_custom_command(
    OUTPUT ${GENERATED_SOURCES}
    COMMAND "./gen_instantiations.py"
    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/gen_instantiations.py ${CMAKE_CURRENT_SOURCE_DIR}/foo.hpp
  )

add_library(
    foo
    foo.cpp
    ${GENERATED_SOURCES}
  )

      

+1


source


Make sure autogen_instantiations.cpp

created in CMAKE_CURRENT_BINARY_DIR

. If the output name is a relative path, it will be interpreted relatively CMAKE_CURRENT_BINARY_DIR

.



If the command does not actually create autogen_instantiations.cpp

in the current binary directory, this rule will always be executed.

+2


source







All Articles