Run a target from a custom target in CMake

I have the following file structure:

├── Generator/
│   ├── output/
│   └── script.py
│
└── FinalProgram/
    ├── build/
    ├── src/
    │   └── main.cpp
    ├── include/
    │   └── MyClass.h
    └── CMakeLists.txt

The Generator/script.py file is a script that generates c++ files in the Generator/output folder. That script can be launched with two different arguments (SimA and SimB), each one generating a different set of files.

On the other hand, the FinalProgram needs to use that set of generated files, so every time I want to compile the FinalProgram with the SimA set of files, I have to

cd Generator 
./script.py SimA
cp output/*.cpp ../FinalProgram/src
cp output/*.h   ../FinalProgram/include
cd ../FinalProgram/build && cmake ..
make

What I want is to be able to type

make SimA

Or

make SimB

So everything happens automatically. In both cases the executable must be the same, so obviously I cannot have two different add_executable blocks. I guess I should create two add_custom_target blocks, one for each possible value, do all the work there and finally call the target that compiles everything. Hence, the real question is, how can I run another target from within an add_custom_target block? Of course, I guess I could use

COMMAND make

But that... that makes me cry. Isn't there a better way?

Upvotes: 1

Views: 6639

Answers (1)

vinograd47
vinograd47

Reputation: 6420

As MadScienceDreams mentioned, you can use add_custom_command to generate the c++ file, then you can use generated file in add_executable command.

add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp
                   COMMAND ${PYTHON_EXECUTABLE} script.py SimA
                   DEPENDS ${CMAKE_SOURCE_DIR}/../Generator/script.py
                   WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/../Generator)

set_property(SOURCE ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp PROPERTY GENERATED TRUE)

add_executable(SimA ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp ...)

add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp
                   COMMAND ${PYTHON_EXECUTABLE} script.py SimB
                   DEPENDS ${CMAKE_SOURCE_DIR}/../Generator/script.py
                   WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/../Generator)

set_property(SOURCE ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp PROPERTY GENERATED TRUE)

add_executable(SimB ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp ...)

For more information see

Upvotes: 1

Related Questions