Issue
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.
Solution
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}")
Answered By - arrowd Answer Checked By - Robin (WPSolving Admin)