如何读取C ++源代码中的CMake变量 [英] How to read a CMake Variable in C++ source code

查看:1020
本文介绍了如何读取C ++源代码中的CMake变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个地方存储我的图书馆的版本号。所以我在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")

使用这个定义,我可以根据Microsoft的定义生成一个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

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.

这篇关于如何读取C ++源代码中的CMake变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆