3

In my CMakeLists.txt, I define a custom target and command:

add_custom_command(
    OUTPUT
        ${CMAKE_CURRENT_SOURCE_DIR}/input.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output1.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output2.csv
    COMMAND python3 
        ${CMAKE_CURRENT_SOURCE_DIR}/tests/genVectors.py)

add_custom_target(TEST_VECTORS
    DEPENDS
        ${CMAKE_CURRENT_SOURCE_DIR}/input.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output1.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output2.csv)

add_executable(VectorTest tests/VectorTest.cpp)
add_dependencies(VectorTest TEST_VECTORS)

It always generates new CSV files even though the files exist. I only need to generate the vectors (with genVectors.py python file) if they do not exist. Is that something wrong with my configuration?

Kevin
  • 16,549
  • 8
  • 60
  • 74
user3691191
  • 547
  • 1
  • 10
  • 20

2 Answers2

2

The OUTPUT option of add_custom_command does not guarantee that the generated files are placed here; it just tells CMake that the generated files are expected to be placed there. It is likely that your python script is generating files at a relative path, so they are just being placed somewhere in your CMake binary directory (your build folder). So while your files may be generated correctly, your custom target doesn't see them because it is looking in CMAKE_CURRENT_SOURCE_DIR. Thus, the custom target will always trigger the custom command to re-run.

CMake runs add_custom_command from the CMAKE_CURRENT_BINARY_DIR by default, but you can change it to run from CMAKE_CURRENT_SOURCE_DIR by adding the WORKING_DIRECTORY option. This way, the generated files will be placed at the expected location, and achieve your desired behavior. Try something like this:

add_custom_command(
    OUTPUT
        ${CMAKE_CURRENT_SOURCE_DIR}/input.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output1.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output2.csv
    COMMAND python3 
        ${CMAKE_CURRENT_SOURCE_DIR}/tests/genVectors.py
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

add_custom_target(TEST_VECTORS
    DEPENDS
        ${CMAKE_CURRENT_SOURCE_DIR}/input.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output1.csv
        ${CMAKE_CURRENT_SOURCE_DIR}/output2.csv)

add_executable(VectorTest tests/VectorTest.cpp)
add_dependencies(VectorTest TEST_VECTORS)
Kevin
  • 16,549
  • 8
  • 60
  • 74
0

You can try to generate your file at time of configuration(i.e. while calling cmake). By this way it will created only once.

You can remove add_custom_command and use execute_process to create your files.

Manthan Tilva
  • 3,135
  • 2
  • 17
  • 41