编译`src`目录源的二进制文件`通过CMake bin`目录(Compile sources in

2019-09-18 02:30发布

我的项目目录包含CMakeLists.txt文件和src ,并include在其根目录下。 src还包含它自己CMakeLists.txt ,这是由一个在根相连。 有没有一种方法,我可以指定CMake的设置默认的全局构建目录,以便在语法src/CMakeLists.txt接近以下?

include_directories(include)
add_executable(first main.cpp foo.cpp)
add_executable(second bar.cpp)

我想建这个目录树:

CMakeLists.txt

src/
    CMakeLists.txt
    main.cpp
    foo.cpp
    bar.cpp

include/
    ...

bin/ (or build/)
    first
    second

Answer 1:

您可以设置CMAKE_RUNTIME_OUTPUT_DIRECTORY

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

然而,这不会内创建子目录bin/为每个不同的目标。

如果你想,你可以创建一个辅助函数来包装add_subdirectories

function(my_add_executable TargetName)
  set(Files ${ARGV})
  list(REMOVE_AT Files 0)
  add_executable(${TargetName} ${Files})
  set_target_properties(${TargetName} PROPERTIES
                            RUNTIME_OUTPUT_DIRECTORY
                                "${CMAKE_SOURCE_DIR}/bin/${TargetName}")
endfunction()

然后简单地改变你的来电:

my_add_executable(first main.cpp foo.cpp)
my_add_executable(second bar.cpp)


欲知详情,请运行

cmake --help-variable "CMAKE_RUNTIME_OUTPUT_DIRECTORY"
cmake --help-property "RUNTIME_OUTPUT_DIRECTORY"
cmake --help-property "RUNTIME_OUTPUT_DIRECTORY_<CONFIG>"


文章来源: Compile sources in `src` directory to binaries in `bin` directory with CMake
标签: cmake