c++ - 在 CMake 中添加多个可执行文件

我在一个 C++ 项目中的代码组织如下

  • 我有几个 .cpp.h 文件,其中包含我的类
  • 我有几个 .cxx 文件必须针对 .cpp 文件和一些外部库进行编译。

现在,每个 .cxx 文件都有一个 main() 方法,所以我需要为每个同名的文件添加一个不同的可执行文件文件。

此外,这些 .cxx 文件可能不会链接到相同的外部库。

我想在 CMake 中编写这个构建,我是一个新手,我该怎么做?

最佳答案

我的建议是分两个阶段解决这个问题:

  1. .cpp.h 文件构建一个库,使用 add_library
  2. 遍历所有 .cxx 文件,并使用 add_executable 从每个文件创建一个可执行文件和 foreach

构建库

这可能很简单

file( GLOB LIB_SOURCES lib/*.cpp )
file( GLOB LIB_HEADERS lib/*.h )
add_library( YourLib ${LIB_SOURCES} ${LIB_HEADERS} )

构建所有可执行文件

只需遍历所有 .cpp 文件并创建单独的可执行文件。

# If necessary, use the RELATIVE flag, otherwise each source file may be listed 
# with full pathname. RELATIVE may makes it easier to extract an executable name
# automatically.
# file( GLOB APP_SOURCES RELATIVE app/*.cxx )
file( GLOB APP_SOURCES app/*.cxx )
foreach( testsourcefile ${APP_SOURCES} )
    # I used a simple string replace, to cut off .cpp.
    string( REPLACE ".cpp" "" testname ${testsourcefile} )
    add_executable( ${testname} ${testsourcefile} )
    # Make sure YourLib is linked to each app
    target_link_libraries( ${testname} YourLib )
endforeach( testsourcefile ${APP_SOURCES} )

一些警告:

  • file(GLOB) 通常不推荐使用,因为如果添加新文件,CMake 不会自动重建。我在这里使用它,因为我不知道你的源文件。
  • 在某些情况下,可以使用完整路径名找到源文件。如有必要,请使用 RELATIVE flag for file(GLOB ...) .
  • 手动设置源文件需要更改 CMakeLists.txt,这会触发重建。见 this question寻找通配符的(缺点)优势。
  • 我使用 string(REPLACE ...) 生成了测试名称。我本可以使用 get_filename_component带有 NAME_WE 标志。

关于“一般”CMake 信息,我建议您阅读一些已在 stackoverflow 上提出的广泛的“CMake 概述”问题。例如:

  • https://stackoverflow.com/questions/2186110/cmake-tutorial
  • What are the dusty corners a newcomer to CMake will want to know?

https://stackoverflow.com/questions/14306642/

相关文章:

ubuntu - 试图包含一个库,但不断收到 'undefined reference to' 消息

visual-studio-2010 - MSbuild 是否需要在构建服务器上安装 Visual

java - Android 构建失败 - java.lang.IllegalArgumentExc

android - 如何将构建时间戳写入apk

c++ - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值

c# - 自动在 Visual Studio c# 项目中嵌入 mercurial 修订信息

build - 构建和构建 OCaml 项目的首选方式是什么?

python - 有没有办法将 python 应用程序编译成静态二进制文件?

c++ - Visual Studio 2010 不会自动链接来自依赖项的项目中的静态库,因为它应该

android - 使用 gradle 签署产品 flavor