使用CMake将`src`目录中的源代码编译为`bin`目录中的二进制文件 [英] Compile sources in `src` directory to binaries in `bin` directory with CMake

查看:912
本文介绍了使用CMake将`src`目录中的源代码编译为`bin`目录中的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目目录包含 CMakeLists.txt 文件和 src include 目录。 src 也包含自己的 CMakeLists.txt ,它由根在一个根链接。有没有办法我可以指定CMake设置默认全局编译目录,使 src / CMakeLists.txt 中的语法接近以下?

My project directory contains a CMakeLists.txt file and src and include directories at its root. src also contains its own CMakeLists.txt, which is linked by the one at the root. Is there a way I can specify to CMake to set a default global build directory so that the syntax in src/CMakeLists.txt is close to the following?

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


推荐答案

您可以设置 CMAKE_RUNTIME_OUTPUT_DIRECTORY

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

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

However, this won't create subdirectories inside bin/ for each different target.

如果你想要的话,你可以创建一个帮助函数来包装 add_subdirectories

If you want that, you could create a helper function to wrap 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()

然后只需将您的来电更改为:

then simply change your calls to:

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



有关详情,请运行


For further details, run

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

这篇关于使用CMake将`src`目录中的源代码编译为`bin`目录中的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆