Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use value from C/C++ macro in CMake

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.

like image 612
usr1234567 Avatar asked Apr 06 '19 11:04

usr1234567


People also ask

Can macro return a value?

Macros just perform textual substitution. They can't return anything - they are not functions.

How do you define a macro in CMake?

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.

How do you set a variable in CMake?

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.

What is Cmake_current_list_dir?

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.


1 Answers

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}")
like image 151
arrowd Avatar answered Sep 28 '22 12:09

arrowd