WINDOWS CMAKE 自定义编译选项

CMake 允许为项目增加编译选项,从而可以根据用户的环境和需求选择最合适的编译方案。

根目录的CMakeLists.txt

cmake_minimum_required (VERSION 3.13)
project(Hello)
set(module_name "hello")

# 查找指定目录下的所有源文件,然后将结果存进指定变量名
aux_source_directory(. SRC_LIST)

include_directories("${PROJECT_SOURCE_DIR}/math")

# 添加 math 子目录
add_subdirectory(math)

# 加入一个配置头文件,用于处理 CMake 对源码的设置
configure_file(
    "${PROJECT_SOURCE_DIR}/config.h.in"
    "${PROJECT_SOURCE_DIR}/config.h"
    )

option(USE_CUSTOM "Use Custom Test" ON)
if(USE_CUSTOM)
    message("USE_CUSTOM ON")
else()
    message("USE_CUSTOM OFF")
endif()

add_executable(${module_name} ${SRC_LIST})

target_link_libraries(${module_name} MathFunctions)

config.h.in

#cmakedefine USE_CUSTOM

main.cpp

#include <iostream>
#include "math/MathFunctions.h"
#include "config.h"
using namespace std;

int main(void)
{
    std::cout<<"hello!"<<std::endl;
    MathFunctions math;
    std::cout<<math.addValue(1, 2)<<std::endl;
#ifdef USE_CUSTOM
    std::cout<<"def USE_CUSTOM"<<std::endl;
#else
    std::cout<<"nodef USE_CUSTOM"<<std::endl;
#endif
    return 0;
}

编译

我们可以试试分别将 USE_CUSTOM 设为 ON 和 OFF 得到的结果
在这里插入图片描述
此时 config.h 的内容为:

#define USE_CUSTOM
在这里插入图片描述

此时 config.h 的内容为:

/* #undef USE_CUSTOM*/

posted @ 2021-11-01 13:43  踏月清风  阅读(118)  评论(0)    收藏  举报