Once a library or executable target has been declared, one can latch additional commands onto the target by using add_custom_command. As we have seen, these commands will be executed at specific times, contextually to the execution of the target they are attached to. CMake understands the following options for the execution order of custom commands:
- PRE_BUILD: For commands to be executed before any other rules pertaining to the target are executed. This is however only supported for Visual Studio 7 or later.
- PRE_LINK: With this option, commands are executed after the target has been compiled but before the linker or archiver are invoked. Using PRE_BUILD with generators other than Visual Studio 7 or later will be interpreted as PRE_LINK.
- POST_BUILD: As already explained, the commands will be run after all the rules for the given target have been executed.
In this example, we have bolted on two custom commands to the executable target. The PRE_LINK command prints the content of ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/example.dir/link.txt to the screen. This file contains the link command and in our example, the link line turned out to be this:
link line:
/usr/bin/f95 -O3 -DNDEBUG -O3 CMakeFiles/example.dir/example.f90.o -o example
We have used a Python wrapper for this to not depend on shell commands, which might not be portable.
In the second step, the POST_BUILD custom command called the Python helper script static-size.py with the generator expression $<TARGET_FILE:example> as argument. CMake will expand the generator expression to the target file path at generation time, that is, when the build system is generated. The Python script static-size.py in turn uses the size command to obtain the size of static allocation of the executable file, converts it to MB, and prints the result. In our case, we obtained the expected 160 MB:
static size of executable:
160.003 MB