CMake生成多个可执行文件

需求

单元测试之类的场景,每个.cc文件就是一个完整的单元测试代码。因此,多个单元测试各自需要编译。即,每个.cc文件都需要编译成可执行文件。

实现

比如,如下的目录结构

├── a.cc
├── b.cc
├── c.cc
├── CMakeLists.txt
└── Makefile

此时,将每个.cc文件编译成可执行文件的CMakeLists.txt文件如下:

cmake_minimum_required(VERSION 3.0.0)
project(cmaketest VERSION 0.1.0)

include_directories("${PROJECT_BINARY_DIR}")

# Find all *.cpp files and store in list native_srcs
file(GLOB_RECURSE native_srcs RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
foreach(srcfile IN LISTS native_srcs)
    # Get file name without directory
    get_filename_component(elfname ${srcfile} NAME_WE)
    add_executable(${elfname} ${srcfile})
endforeach()
posted @ 2022-07-15 16:54  时间的风景  阅读(2032)  评论(0编辑  收藏  举报