Skip to content

CMake条件编译

通过不同传入参数编译不同的文件

  1. 用option定义变量
  2. 在子CMakeLists.txt中根据变量ON还是OFF来修改SRC(源文件)以及target_compile_definitions
  3. 修改源文件根据变量选择代码
  4. 执行命令时使用-D <变量> =ON/OFF来进行条件编译

说明PUBLICINTERFACEPRIVATE的区别

  • PUBLIC:本目标需要用,依赖这个目标的其他目标也需要
  • INTERFACE:本目标不需要,依赖这个目标的其他目标需要
  • PRIVATE:本目标需要,依赖这个目标的其他目标不需要

案例展示

环境构建

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

1 directory, 4 files

$ cat CMakeLists.txt 
cmake_minimum_required(VERSION 3.20.0)

project(test)

option(TEST_CMP "Test conditional compilation" ON)
if(TEST_CMP)
    set(SRC main.cpp test.cpp)
else()
    set(SRC main.cpp)
endif()

add_executable(test ${SRC})

if(TEST_CMP)
    target_compile_definitions(test PRIVATE "TEST_CMP")
endif()

$ cat main.cpp 
#ifdef TEST_CMP
#include "test.h"
#endif

#include <iostream>

int main(int argc, char *argv[]) {
    std::cout << "main print" << std::endl;

#ifdef TEST_CMP
    test();
#endif

    return 0;
}

$ cat test.h 
#pragma once

void test();

$ cat test.cpp
#include "test.h"
#include <iostream>

void test() {
    std::cout << "call test" << std::endl;
}

默认情况下TEST_CMP=ON,执行cmake -B build cmake --build build build/test会输出

shell
main print
call test

但是如果执行cmake -B build的时间把TEST_CMP设置为OFF就会输出(cmake -B build -D TEST_CMP=OFF

shell
main print