How to read a CMake Variable in C++ source code

The easiest way to do this, is to pass the LIBINTERFACE_VERSION as a definition with add_definition:

add_definitions( -DVERSION_LIBINTERFACE=${LIBINTERFACE_VERSION} )

However, you can also create a “header-file template” and use configure_file. This way, CMake will replace your @LIBINTERFACE_VERSION@. This is also a little more extensible because you can easily add extra defines or variables here…

E.g. create a file “version_config.h.in”, looking like this:

#ifndef VERSION_CONFIG_H
#define VERSION_CONFIG_H

// define your version_libinterface
#define VERSION_LIBINTERFACE @LIBINTERFACE_VERSION@

// alternatively you could add your global method getLibInterfaceVersion here
unsigned int getLibInterfaceVersion()
{
    return @LIBINTERFACE_VERSION@;
}

#endif // VERSION_CONFIG_H

Then add a configure_file line to your cmakelists.txt:

configure_file( version_config.h.in ${CMAKE_BINARY_DIR}/generated/version_config.h )
include_directories( ${CMAKE_BINARY_DIR}/generated/ ) # Make sure it can be included...

And of course, make sure the correct version_config.h is included in your source-files.

Leave a Comment