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

2024-04-13

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

  • 我有一些.cpp and .h包含我的课程的文件
  • 我有一些.cxx必须针对以下内容进行编译的文件.cpp文件和一些外部库。

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

还有,这些.cxx文件可能无法链接到相同的外部库。

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


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

  1. 建立一个图书馆.cpp and .h文件,使用add_library https://cmake.org/cmake/help/latest/command/add_library.html
  2. 迭代你所有的.cxx文件并使用每个文件创建一个可执行文件add_executable https://cmake.org/cmake/help/latest/command/add_executable.html and foreach https://cmake.org/cmake/help/latest/command/foreach.html

建立图书馆

这可能很简单

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} )
    # Cut off the file extension and directory path
    get_filename_component( testname ${testsourcefile} NAME_WE )
    add_executable( ${testname} ${testsourcefile} )
    # Make sure YourLib is linked to each app
    target_link_libraries( ${testname} YourLib )
endforeach( testsourcefile ${APP_SOURCES} )

一些警告:

  • file( GLOB )通常不推荐,因为如果添加新文件,CMake 不会自动重建。我在这里使用它,因为我不知道你的源文件。
  • 在某些情况下,可能会找到具有完整路径名的源文件。如有必要,请使用相对标志file(GLOB ...) https://cmake.org/cmake/help/latest/command/file.html#glob.
  • 手动设置源文件需要更改 CMakeLists.txt,这会触发重建。看这个问题 https://stackoverflow.com/questions/1027247/best-way-to-specify-sourcefiles-in-cmake对于(通配符的缺点。

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

  • https://stackoverflow.com/questions/2186110/cmake-tutorial https://stackoverflow.com/questions/2186110/cmake-tutorial
  • CMake 新手想了解哪些尘土飞扬的角落? https://stackoverflow.com/questions/4506193/what-are-the-dusty-corners-a-newcomer-to-cmake-will-want-to-know
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 CMake 中添加多个可执行文件 的相关文章

随机推荐