我目前正在使用递归 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/