What is the easiest way to get the value of a C/C++ macro into a CMake variable?
Given I check for a library libfoo
with the header foo.h
. I know foo.h
contains the macro #define FOO_VERSION_MAJOR <version>
where version is an integer or string value. To extract the major version of the found library, I want to use the value from this macro.
As a bonus, if the macro is not found, this could indicate a version older then a specific version introducing the version macro.
Macros just perform textual substitution. They can't return anything - they are not functions.
If you are using CMake 3. X your first choice for adding a preprocessor macro should be target_compile_definitions. The reason you should prefer this approach over any other approach is because it granularity is target based. IE the macro will only be added to your exe/library.
Options and variables are defined on the CMake command line like this: $ cmake -DVARIABLE=value path/to/source You can set a variable after the initial `CMake` invocation to change its value. You can also undefine a variable: $ cmake -UVARIABLE path/to/source Variables are stored in the `CMake` cache.
CMAKE_CURRENT_LIST_DIR: Full directory of the listfile currently being processed. As CMake processes the listfiles in your project this variable will always be set to the directory where the listfile which is currently being processed (CMAKE_CURRENT_LIST_FILE) is located. The value has dynamic scope.
I'd go with file(READ ...)
to read the header followed by string(REGEX ...)
to extract desired define.
Example code:
file(READ "foo.h" header)
string(REGEX MATCH "#define FOO_MAJOR_VERSION [0-9]+" macrodef "${header}")
string(REGEX MATCH "[0-9]+" FooMajorVersion "${macrodef}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With