我正在学习 CMake,并一直试图了解如何将作为单独项目的静态库链接到可执行文件,然后配置根项目以正确收集所有可执行目标的依赖项并构建所有可执行文件。
我的层次结构是这样的:
.
├── app
│ ├── CMakeLists.txt
│ ├── build
│ ├── include
│ └── src
│ └── main.cpp
├── square
│ ├── CMakeLists.txt
│ ├── build
│ ├── include
│ │ └── lolerji_square.h
│ └── src
│ └── lolerji_square.cpp
└── CMakeLists.txt
现在,我的目标是在这个层次结构中拥有几个不同的应用程序,类似于
app
和许多静态库,例如 square
。每个应用程序都可以引用此层次结构中的任何静态库。但是,我不知道如何配置 CMakeLists.txt
文件。
目标是允许单独维护每个依赖项,而在构建可执行文件时,如果需要,可以从源代码编译每个依赖项。我想用尽可能最现代的方法来实现这一目标。具体来说,如果可能的话,我想避免使用
add_subdirectory()
和 include_directories()
,因为据我了解,它们可能会带来我宁愿避免的恶作剧。
我对 CMake 相当陌生,我的方法可能是错误的。即便如此,我很高兴知道这是否可以实现,如果可以的话如何实现,如果这不是解决此类问题的推荐方法,那么最好的方法是什么。
我设法构建了结构。
首先,我配置了每个库,以便它们都有
src
和 include
目录。头文件对于构建以及提供接口是必需的。
库CMakeLists.txt
cmake_minimum_required(VERSION 3.27)
project(<folder name>)
add_library(<folder name>lib STATIC)
target_sources(<folder name>lib PRIVATE src/source1.cpp src/source2.cpp ...)
target_include_directories(<folder name>lib PUBLIC include)
然后,对于可执行项目:
cmake_minimum_required(VERSION 3.27)
project(<folder name>)
add_executable(<folder name>)
target_sources(<folder name> PRIVATE src/main.cpp src/othersource.cpp ...)
target_link_libraries(<folder name> PRIVATE lib1 lib2 ...)
在根CMakeLists.txt中
cmake_minimum_required(VERSION 3.27)
project(<folder name>)
add_subdirectory(lib1)
add_subdirectory(lib2)
# add other libs here...
add_subdirectory(app1)
add_subdirectory(app2)
# add other executables here...
然后,在根目录中使用
cmake -S . -B build
,我可以将所有库和可执行文件构建为单独的项目,并将所有内容都放在 ./build 下
但是,这种方法每次都会编译所有源代码,因此如果库需要很长时间才能编译,我认为这种方法并不理想。