且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何读取C ++源代码中的CMake变量

更新时间:2022-05-23 23:46:56

最简单的方法是传递LIBINTERFACE_VERSION作为一个定义 add_definition

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

add_definitions( -DVERSION_LIBINTERFACE=${LIBINTERFACE_VERSION} )

但是,您也可以创建头文件模板请使用 configure_file 。这样,CMake将替换你的@ 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...

例如。创建一个文件version_config.h.in,如下所示:

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

configure_file行到您的cmakelists.txt:

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...

当然,请确保您的源文件中包含正确的version_config.h。

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