且构网

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

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

更新时间:2022-05-23 23:47:08

最简单的方法是将 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

然后在您的 cmakelists.txt 中添加一个 configure_file 行:

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.