Let us have a look at our CMakeLists.txt:
- We first declare a Fortran project:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-05 LANGUAGES Fortran)
- This example depends on the Python interpreter so that we can execute the helper scripts in a portable fashion:
find_package(PythonInterp REQUIRED)
- In this example, we default to the "Release" build type so that CMake adds optimization flags so that we have something to print later:
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
- Now, we define the executable target:
add_executable(example "")
target_sources(example
PRIVATE
example.f90
)
- We then define a custom command to print the link line before the example target is linked:
add_custom_command(
TARGET
example
PRE_LINK
COMMAND
${PYTHON_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/echo-file.py
${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/example.dir/link.txt
COMMENT
"link line:"
VERBATIM
)
- Finally, we define a custom command to print the static size of the executable after it has been successfully built:
add_custom_command(
TARGET
example
POST_BUILD
COMMAND
${PYTHON_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/static-size.py
$<TARGET_FILE:example>
COMMENT
"static size of executable:"
VERBATIM
)
- Let us test it out. Observe the printed link line and static size of executable:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
Scanning dependencies of target example
[ 50%] Building Fortran object CMakeFiles/example.dir/example.f90.o
[100%] Linking Fortran executable example
link line:
/usr/bin/f95 -O3 -DNDEBUG -O3 CMakeFiles/example.dir/example.f90.o -o example
static size of executable:
160.003 MB
[100%] Built target example