Calling existing make command in cmake file

cmakemakefile

I have a large project with multiple subdirectories. In the parent directory, I have a CMakeLists.txt file which calls functions defined in other cmake files in the same parent directory. I have a custom Makefile in one of the subdirectories that contains some target "run". When I call cmake from the parent directory, I want the "run" target located in the subdirectory makefile to execute. How should I do this? I understand that some people have suggested to use add_custom_target and add_custom_command, but I am still confused as to how to apply these commands to accomplish this task.

Best Answer

If you know, which file(s) are produced by Makefile in the subdirectory, and want to depend on these files, use add_custom_command:

add_custom_command(OUTPUT <output-file>
                   COMMAND make run
                   WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/<subdir>
)

This assumes that your CMakeLists.txt have a target, which depends or uses given file.

Otherwise, if you do not care which files are produced by Makefile, use add_custom_target:

add_custom_target(<target_name> COMMAND make run
                   WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/<subdir>
)

In both cases WORKING_DIRECTORY specifies directory which should be current for command executed.

If you want the target (in the second case) to be executed by default, add ALL option before the COMMAND.