c - CMake下的多个目录

我目前正在使用递归 make 和 autotools,并希望迁移到 CMake 的项目看起来像这样:

lx/ (project root)
    src/
        lx.c (contains main method)
        conf.c
        util/
            str.c
            str.h
            etc.c
            etc.h
        server/
            server.c
            server.h
            request.c
            request.h
        js/
            js.c
            js.h
            interp.c
            interp.h
    bin/
        lx (executable)

我该怎么办?

最佳答案

如果从来没有任何高于 lx/src 目录的源,则不需要 lx/CMakeLists.txt 文件。如果有,它应该看起来像这样:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(lx)

add_subdirectory(src)
add_subdirectory(dir1)
add_subdirectory(dir2)

# And possibly other commands dealing with things
# directly in the "lx" directory

...子目录按库依赖顺序添加。应该首先添加不依赖任何其他内容的库,然后添加依赖这些内容的库,依此类推。

lx/src/CMakeLists.txt

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(lx_exe)

add_subdirectory(util)
add_subdirectory(js)
add_subdirectory(server)

set(lx_source_files conf.c lx.c)
add_executable(lx ${lx_source_files})

target_link_libraries(lx server)
  # also transitively gets the "js" and "util" dependencies

lx/src/util/CMakeLists.txt

set(util_source_files
  etc.c
  etc.h
  str.c
  str.h
)
add_library(util ${util_source_files})

lx/src/js/CMakeLists.txt

set(js_source_files
  interp.c
  interp.h
  js.c
  js.h
)
add_library(js ${js_source_files})

target_link_libraries(js util)

lx/src/server/CMakeLists.txt

set(server_source_files
  request.c
  request.h
  server.c
  server.h
)
add_library(server ${server_source_files})

target_link_libraries(server js)
  # also transitively gets the "util" dependency

然后,在命令提示符中:

mkdir lx/bin
cd lx/bin

cmake ..
  # or "cmake ../src" if the top level
  # CMakeLists.txt is in lx/src

make

默认情况下,lx 可执行文件将使用这种精确的布局在“lx/bin/src”目录中结束。您可以使用 RUNTIME_OUTPUT_DIRECTORY 目标属性和 set_property 命令来控制它最终位于哪个目录。

http://www.cmake.org/cmake/help/cmake-2-8-docs.html#prop_tgt:RUNTIME_OUTPUT_DIRECTORY

http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:set_property

如果通过 add_library 将库构建为 CMake 目标,则通过 CMake 目标名称引用 target_link_libraries 库,否则通过库文件的完整路径。

另请参阅“cmake --help-command target_link_libraries”或任何其他 cmake 命令的输出,以及此处找到的 cmake 命令的完整在线文档:

http://www.cmake.org/cmake/help/cmake-2-8-docs.html#section_Commands

http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:target_link_libraries

https://stackoverflow.com/questions/6352123/

相关文章:

build - 如何将 build.gradle 目录传递给 gradlew?

java - 如何使用 pom.xml 将参数传递给 Maven 构建?

.net - 使用 Nant 构建 .NET 4 项目

build - 有 CMake 递归扫描文件夹吗?

c# - Visual Studio 中的 "build"和 "rebuild"有什么区别?

java - 使用 SBT 构建纯 Java 项目

visual-studio - 使用 Installshield LE 包含标记为 "Copy to

git - Jenkins:一个项目的多个 Git 存储库

xcode - 在需要时配置 Xcode 4 工作区以构建依赖项的正确方法是什么?

c++ - 在编译时使用 C++ 在目标代码中嵌入时间戳