C++文件中使用CmakeLists中定义的变量的第二种方法

本文介绍如何使用CMakeLists.txt文件定义版本号等变量,并通过配置文件config.h.in生成对应的header文件config.h,实现在C++项目中引用这些变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CMakeLists.txt

 

Adding such variables can be implemented by creating a configuration file with the extension h.in in which define directives will be defined, which will be added by constants from CMakeLists.txt in C ++. In this case, the corresponding header file will be generated.

cmake_minimum_required (VERSION 3.8)

project (VariablesProject)

# Add the variables we need
set (VERSION_MAJOR 0)
set (VERSION_MINOR 1)
set (VERSION_PATCH 0)
set (SOFT_VERSION $ {VERSION_MAJOR}. $ {VERSION_MINOR}. $ {VERSION_PATCH})

# Specify the configuration file from which the header file will be generated
configure_file (config.h.in config.h @ONLY)

add_executable ($ {PROJECT_NAME} main.cpp)

# add a directory with header files to see the generated file
include_directories ($ {CMAKE_CURRENT_BINARY_DIR})

config.h.in

The configuration file from which the header file config.h will be generated.

#ifndef CONFIG_H_IN
#define CONFIG_H_IN

#define PROJECT_NAME @ PROJECT_NAME @
#define VERSION_MAJOR "@ VERSION_MAJOR @"
#define VERSION_MINOR "@ VERSION_MINOR @"
#define VERSION_PATCH "@ VERSION_PATCH @"
#define SOFT_VERSION "@ SOFT_VERSION @"

#endif // CONFIG_H_IN

main.cpp

#include <iostream>

#include "config.h" // Add an automatically generated configuration file

int main ()
{
    // Use variables from CMakeLists.txt
    std :: cout << "project name:" << PROJECT_NAME << std :: endl;
    std :: cout << "version:" << SOFT_VERSION << std :: endl;
    std :: cout << "version major:" << VERSION_MAJOR << std :: endl;
    std :: cout << "version minor:" << VERSION_MINOR << std :: endl;
    std :: cout << "version patch:" << VERSION_PATCH << std :: endl;
    return 0;
}

Program output

We get the following output in the console as a result.

project name: VariablesProject
version: 0.1.0
version major: 0
version minor: 1
version patch: 0

UPD

The config.h file will be generated in the build directory, if you want to create it in the source directory, write this

configure_file(config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config.h @ONLY)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值