目录
说明
在开发过程碰到需要在上级目录中构建,而源代码又分别写在下级目录的情况,同时又要根据不同的情况选择性地添加不同的源代码进行编译,所以考虑将需要编译的源代码放到一个 cmake 列表中。但是 set() 对应生成的变量都是局部变量(即不同的目录下不共用),于是使用 set_property() 命令。
简单示例
为了简化,我这里假设在 main() 函数下调用一个 show_system() 函数用于显示当前系统的名称。程序整体结构如下:
$ tree
├── CMakeLists.txt
├── linux
│ ├── CMakeLists.txt
│ ├── property.c
│ └── property.h
├── main.c
└── win
├── CMakeLists.txt
├── property.c
└── property.h
main.c
程序很简单,就调用子目录下定义的函数。
#include <stdio.h>
#include <property.h>
int main()
{
show_system();
return 0;
}
property.c
在 linux 和 win 的实现都一样。
#include <stdio.h>
#include "property.h"
void show_system()
{
printf("This is linux\n"); // in linux
printf("This is windows\n"); // in win
}
根目录下的 CMakeLists.txt
cmake_minimum_required (VERSION 3.13.0)
project (property_test VERSION 0.0.4)
# 设置全局属性 SOURCE_LIST
set_property( GLOBAL APPEND PROPERTY SOURCE_LIST)
# 如果是 Linux 系统,选择编译 linux 目录
IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
include_directories (linux)
add_subdirectory (linux)
# Window 系统下选择编译 win 目录
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
include_directories (win)
add_subdirectory (win)
ENDIF (CMAKE

本文介绍了如何在CMake中利用set_property()和get_property()命令,根据不同操作系统动态选择子目录并附加源文件到编译列表,实现源代码的有条件编译。示例详细展示了如何在Linux和Windows下分别处理property.c文件,并通过CMakeLists.txt进行管理。
最低0.47元/天 解锁文章
1635

被折叠的 条评论
为什么被折叠?



