如何在 C++ 源代码中读取 CMake 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7900661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a CMake Variable in C++ source code
提问by Snowfox
I'd like to store the version number of my library in just one place. So I have defined such a variable in the CMake-file:
我想将我的库的版本号存储在一个地方。所以我在 CMake 文件中定义了这样一个变量:
SET(LIBINTERFACE_VERSION 1 CACHE INTEGER "Version of libInterface")
With this definition I can generate a version.rc file according to Microsoft's definition, which I compile into the library and afterwards shows up correctly in the properties window of my dll-file.
有了这个定义,我可以根据微软的定义生成一个 version.rc 文件,我将它编译到库中,然后在我的 dll 文件的属性窗口中正确显示。
Now I'd like to use this CMake variable in my c++ source code too, but I actually don't get to a working solution. I've tried different things like this:
现在我也想在我的 C++ 源代码中使用这个 CMake 变量,但我实际上没有找到一个可行的解决方案。我尝试过这样的不同事情:
#ifndef VERSION_LIBINTERFACE
# define VERSION_LIBINTERFACE @LIBINTERFACE_VERSION@
#endif
or this:
或这个:
unsigned int getLibInterfaceVersion()
{
return @LIBINTERFACE_VERSION@;
}
But the compiler won't accept anything. Since my researches in the CMake-Documentation didn't get any results, I hope that someone could give me the essential advice.
但是编译器不会接受任何东西。由于我在 CMake-Documentation 中的研究没有得到任何结果,我希望有人能给我一些重要的建议。
Thanks in advance.
提前致谢。
回答by André
The easiest way to do this, is to pass the LIBINTERFACE_VERSION as a definition with add_definition:
最简单的方法是将 LIBINTERFACE_VERSION 作为定义传递给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...
但是,您也可以创建“头文件模板”并使用configure_file。这样,CMake 将替换您的 @LIBINTERFACE_VERSION@。这也更具可扩展性,因为您可以在此处轻松添加额外的定义或变量...
E.g. create a file "version_config.h.in", looking like this:
例如创建一个文件“version_config.h.in”,如下所示:
#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 行添加到您的 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.
当然,请确保您的源文件中包含正确的 version_config.h。