Skip to content

CMake与源文件交互

CMake与源文件进行交互一个非常重要的应用就是CMake可以获取环境变量重的一些信息,与源文件交互传递给源文件使用,源文件则可以根据不同的环境变量执行不同的逻辑代码。

案例展示

shell
$ tree
.
├── CMakeLists.txt
├── config.h.in
└── main.cpp

1 directory, 3 files


$ cat CMakeLists.txt 
cmake_minimum_required(VERSION 3.20.0)

project(test)

set(CMAKE_CXX_STANDARD 11)

configure_file(config.h.in config.h)

add_executable(test
    main.cpp
)

# 需要设置可执行程序的目录为include目录main.cpp中才可正确引入config.h进行使用
target_include_directories(test PUBLIC ${PROJECT_BINARY_DIR})


$ cat config.h.in 
#define CXX_STANDARD ${CMAKE_CXX_STANDARD}

#define PROJECT "${CMAKE_PROJECT_NAME}"
#define VERSION "${CMAKE_VERSION}"
#define BINARY_DIR "${PROJECT_BINARY_DIR}"
#define SOURCE_DIR "${PROJECT_SOURCE_DIR}"

#define SYSTEM_NAME "${CMAKE_SYSTEM_NAME}"


$ cat main.cpp 
#include "config.h"
#include <iostream>
#include <string>

int main(int argc, char *argv[]) {
    std::cout << "CXX_STANDARD: " << CXX_STANDARD << std::endl;
    std::cout << "PROJECT_NAME: " << PROJECT << std::endl;
    std::cout << "CMAKE_VERSION: " << VERSION << std::endl;
    std::cout << "BINARY_DIR: " << BINARY_DIR << std::endl;
    std::cout << "SOURCE_DIR: " << SOURCE_DIR << std::endl;

    std::string systemInfo(SYSTEM_NAME);
    auto idx = systemInfo.find("Linux");
    if(idx!=std::string::npos){
        std::cout << "欢迎Linux用户运行程序" << std::endl;
    }

    idx = systemInfo.find("Windows");
    if (idx != std::string::npos) {
        // Windows下控制台输出中文会显示乱码🥲 直接使用英文算了
        std::cout << "Windows user is running program" << std::endl;
    }

    idx = systemInfo.find("Darwin");
    if (idx != std::string::npos) {
        std::cout << "欢迎Mac用户运行程序" << std::endl;
    }

    return 0;
}