<< Modern CMake >> 2.3 to communicate with the code translation
Profiles
CMake allows you to use the code by configure_file
accessing CMake variables. This command copies of a document is usually the .in
suffix copy files from one place to another, which replaces all variables CMake. If you want to avoid your input file existing ${}
replacement carried out, you can use @ONLY
keywords. There is also a COPY_ONLY
keyword, you can just substitute file(COPY
use.
This feature is very frequently used; for example, in the Version.h.in
file:
Version.h.in
#pragma once
#define MY_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
#define MY_VERSION_MINOR @PROJECT_VERSION_MINOR@ #define MY_VERSION_PATCH @PROJECT_VERSION_PATCH@ #define MY_VERSION_TWEAK @PROJECT_VERSION_TWEAK@ #define MY_VERSION "@PROJECT_VERSION@"
CMake file lines:
configure_file (
"${PROJECT_SOURCE_DIR}/include/My/Version.h.in"
"${PROJECT_BINARY_DIR}/include/My/Version.h"
)
When building the project, it should also include the directory containing the binary. To place any true / false variable in the header file, CMake a dedicated C-specific #cmakedefine
and #cmakedefine01
replacement to be defined appropriately.
You can also (and often) use it to generate .cmake
documents, such as configuration files (See configuration section section).
Reading information from the code files
The other direction can do; you can read some of the content (such as version) from the source file. For example, if you have a pure head-link library file, you may or may not use CMake, then this will be the best way to handle version.
Write it like this:
# Assuming the canonical version is listed in a single line
# This would be in several parts if picking up from MAJOR, MINOR, etc.
set(VERSION_REGEX "#define MY_VERSION[ \t]+\"(.+)\"")
# Read in the line containing the version file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/My/Version.hpp" VERSION_STRING REGEX ${VERSION_REGEX}) # Pick out just the version string(REGEX REPLACE ${VERSION_REGEX} "\\1" VERSION_STRING "${VERSION_STRING}") # Automatically getting PROJECT_VERSION_MAJOR, My_VERSION_MAJOR, etc. project(My LANGUAGES CXX VERSION ${VERSION_STRING})
Construction of the above, the file(STRINGS file_name variable_name REGEX regex)
selected regular expression matching lines; and using the same regex capture group selecting section extracts version information. Alternatively use with the rear output to replace only the set.