Custom Commands and Targets
Introduction
CMake allows you to define custom commands and custom targets to perform tasks that aren’t part of the standard build process. For example:
- Generating source files from a script.
- Running a code formatter or linter.
- Copying files or running post-build steps.
Key Concepts
add_custom_command()
: Defines a command to run at a specific stage of the build (e.g., before or after building a target).add_custom_target()
: Creates a new target that can be invoked manually (e.g.,make my_target
) and can depend on other targets or commands.OUTPUT
andDEPENDS
: Used to specify files generated by the command and dependencies for the command.
Code Sample
- Let's start by creating
makehello.cpp
which will generate a simple function for us.
- Let's create a
makehello.cmake
file which will create aMakeHello
executable from makehello.cpp and run it using the custom command feature to finally generate ourhello.h
file.
Notice above how OUTPUT
specifies that hello.h
will be generated in the bin directory (called build
in our case). This helps CMake decide when to run this custom command - i.e. whenever something references hello.h
- Let's edit the
main.cpp
file to call thesayHello
function which will be defined inhello.h
when it is generated. Your editor will indicate thathello.h
is missing for now.
- Finally, let's edit the CMakeLists.txt file to include the makehello.cmake file.
- Run cmake and build.
You should find hello.h
in the build
directory and everything should compile nicely.
- Output: