cmake03-熟悉target_compile_definitions

494 阅读1分钟

人们往往关心如何向工程中加入预处理器定义: 比如_WINDOWS之类的。 这里展示一种做法。

CMakeList.txt代码:

cmake_minimum_required(VERSION 3.15)

project ( hello_world_prj )

set( EXE_SOURCES
    src/main.cpp
    src/Hello.cpp
)

add_executable( hello_world_exe  ${EXE_SOURCES} )

target_include_directories( hello_world_exe
    PRIVATE 
        ${PROJECT_SOURCE_DIR}/include
)

target_compile_definitions( hello_world_exe PRIVATE MY_DEF1 )
target_compile_definitions( hello_world_exe PRIVATE MY_DEF2 )
target_compile_definitions( hello_world_exe PRIVATE MY_DEF3 )
target_compile_definitions( hello_world_exe
                            PRIVATE 
                                  MY_DEF4
                                  MY_DEF5
                                  MY_DEF6
                                  )

add_executable( hello_world_exe_1024  ${EXE_SOURCES} )

target_include_directories( hello_world_exe_1024
    PRIVATE 
        ${PROJECT_SOURCE_DIR}/include
)

target_compile_definitions( hello_world_exe_1024 PRIVATE HELLO_DEF1 )
target_compile_definitions( hello_world_exe_1024 PRIVATE HELLO_DEF2 )

Win10下使用powershell:

cmake ../

cmake --build . --config release

用vs2019打开工程有:

可以看到有两个工程项目:

hello_world_exe和hello_world_exe_1024

分别点击各个项目属性,进入到预处理项,有:

hello_world_exe:

可见,MY_DEF1,MY_DEF2等自定义预处理项都已经加入工程。

对于hello_world_exe_1024,有:

可见,HELLO_DEF1,HELLO_DEF1等自定义预处理项都已经加入工程。

这样,对于target_compile_definitions的基本使用有了写感性认识,这是祛魅的方法,剩下的就是时间问题了。