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

时间:2013-01-13 18:20:25

标签: c++ build cmake executable

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

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

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

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

我想在CMake中编写这个版本,我是一个新手,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:88)

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

  1. 使用add_library
  2. .cpp.h文件构建库
  3. 遍历所有.cxx个文件,并使用add_executableforeach
  4. 从每个文件创建可执行文件

    构建库

    这可能就像

    一样简单
    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 find( GLOB ... )
    • 手动设置源文件需要更改CMakeLists.txt,这会触发重建。有关globbing的(dis-)优点,请参阅this question
    • 我使用string( REPLACE ... )生成了testname。我可以将get_filename_componentNAME_WE标志一起使用。

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

答案 1 :(得分:0)

CMakeLists.txt适用于我的OpenCV项目
假设*.cpp个文件与CMakeLists.txt处于同一目录

cmake_minimum_required(VERSION 3.5)

project(opencv LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(OpenCV REQUIRED)
include_directories( ${OpenCV_INCLUDE_DIRS} )

file( GLOB APP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp )
foreach( sourcefile ${APP_SOURCES} )
    file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${sourcefile})
    string( REPLACE ".cpp" "" file ${filename} )
    add_executable( ${file} ${sourcefile} )
    target_link_libraries( ${file} ${OpenCV_LIBS} )
endforeach( sourcefile ${APP_SOURCES} )