casparjespersen
casparjespersen

Reputation: 3830

CMake: Executing a C++ file when building the project

I am developing on a C++ project, and I want to execute a script on build to generate some files. I am not very familiar with CMake, so I need some help.

And by script I mean a .cpp file within the project.

I have managed to obtain the following:

   set(PrecisionCommand
      ${CMAKE_SOURCE_DIR}/src/main/matlab/matlabprecision.cpp
   )
   set(precision_output_files
      ${CMAKE_SOURCE_DIR}/work/variables.txt
   )

   add_custom_command(
      OUTPUT ${precision_output_files}
      COMMAND ${PrecisionCommand}
      COMMENT "Running ${PrecisionCommand}"
   )


   add_custom_target(allocate_generate DEPENDS ${precision_output_files})

And what happens now is that the matlabprecision.cpp file is being opened in a text editor, rather than being executed. How do I fix this?

Upvotes: 1

Views: 766

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65870

Because .c file is not a script but a source file, you cannot directly execute it. However, you may first compile it into executable:

add_executable(PrecisionCommand ${CMAKE_SOURCE_DIR}/src/main/matlab/matlabprecision.cpp)

and then run that executable:

add_custom_command(
  OUTPUT ${precision_output_files}
  COMMAND PrecisionCommand
  COMMENT "Running PrecisionCommand"

)

Note, that COMMAND option uses target name for run the executable. CMake understand that usage and:

  • Transform target name into the path to the executable.
  • Add appropriate dependencies between creating executable and running it.

From documentation about add_custom_command:

If COMMAND specifies an executable target (created by ADD_EXECUTABLE) it will automatically be replaced by the location of the executable created at build time. Additionally a target-level dependency will be added so that the executable target will be built before any target using this custom command.

Upvotes: 1

Related Questions