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

2021-12-26 00:00:00 makefile cmake c++ header-files

我想将我的库的版本号存储在一个地方.所以我在 CMake 文件中定义了这样一个变量:

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:

    SET(LIBINTERFACE_VERSION 1 CACHE INTEGER "Version of libInterface")

有了这个定义,我可以根据微软的定义生成一个 version.rc 文件,我将其编译到库中,然后在我的 dll 文件的属性窗口中正确显示.

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.

现在我也想在我的 C++ 源代码中使用这个 CMake 变量,但我实际上没有找到一个可行的解决方案.我尝试过类似这样的不同事情:

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:

    #ifndef VERSION_LIBINTERFACE
    #  define VERSION_LIBINTERFACE @LIBINTERFACE_VERSION@
    #endif

或者这个:

    unsigned int getLibInterfaceVersion()
    {
        return @LIBINTERFACE_VERSION@;
    }

但是编译器不会接受任何东西.由于我在 CMake-Documentation 中的研究没有得到任何结果,我希望有人能给我一些重要的建议.

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.

提前致谢.

推荐答案

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

相关文章