如何正确设置CMake项目?

Lay*_*way 5 c++ cmake

虽然很容易找到关于如何使用CMake的表面级信息,但是如何正确使用CMake的信息似乎很难找到.如何在一个体积适中的CMake项目(一个可执行文件,该可执行文件使用的一个或多个静态库,静态库使用的一个或多个外部依赖项)中对文件夹和CMakeList.txt文件进行排序?什么CMakeList.txt文件应该有什么命令?

Tar*_*ama 3

学习如何有效使用 CMake 的一个好方法是查看其他项目。LLVM及其子项目就是一个很好的例子。

一般来说,良好的编码实践会转化为良好的 CMake 实践;您想要模块化、清晰的风格和灵活性。

一个示例可能是制定在src目录内构建可执行文件的规则,然后在根项目文件夹中使用该目标。像这样的东西:

-my_proj
|
----CMakeLists.txt //contains directives for top-level dependencies and linking, includes subfolders
----src
    |
    ----CMakeLists.txt //contains definition of your main executable target
    ----internal_lib
        |
        ----CMakeLists.txt //contains definition of your internal static libraries
Run Code Online (Sandbox Code Playgroud)

my_proj/CMakeLists.txt

add_subdirectory(src)
find_package (Threads REQUIRED) #find pthreads package
target_link_libraries (my_exe my_lib ${CMAKE_THREAD_LIBS_INIT}) #link against pthreads and my_lib
Run Code Online (Sandbox Code Playgroud)

my_proj/src/CMakeLists.txt

add_subdirectory(internal_lib)
add_executable(my_exe my_source1.cpp mysource2.cpp)
Run Code Online (Sandbox Code Playgroud)

my_proj/src/internal_lib/CMakeLists.txt

add_library(my_lib my_lib_source1.cpp my_lib_source2.cpp)
Run Code Online (Sandbox Code Playgroud)