我对CMake很新,想要创建一个需要一些第三方库的小项目。我希望将这些库作为git仓库以保持最新状态。有些库只是.cpp和.hpp文件(如glad、imgui),而另一些则是cmake项目(如glfw、glm)。
我的想法是建立一个第三方项目,其中包含所有的库,作为子项目;同时建立一个沙盒项目来使用这些库,并包含等等。我希望使用现代的CMake代码,不会在框架结构外安装任何东西。
文件夹结构:
Framework
|--3rd_party
| |--glad
| | |--include
| | |--src
| |--glfw-master
| | |--...
| | |--CMakeLists.txt
| |--glm-master
| | |--..
| | |--CMakeLists.txt
| |--imgui-master
| | |--*.cpp
| | |--*.hpp
| | |--examples
| | | |--*.cpp
| | | |--*.hpp
| |--CMakeLists.txt
|--sandbox
| |--main.cpp
| |--CMakeLists.txt
|--CMakeLists.txt
我创建了这个文件夹结构,并编写了一些CMakeLists文件:
CMakeLists.txt(框架)
cmake_minimum_required(VERSION 3.10)
project(Framework)
add_subdirectory("3rd_party")
add_subdirectory("sandbox")
CMakeLists.txt(第三方)
#GLFW
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(glfw-master)
# GLM
set(GLM_TEST_ENABLE OFF CACHE BOOL "" FORCE)
add_subdirectory(glm-master)
# Glad
add_library(
Glad STATIC
"glad/src/glad.c"
)
target_include_directories(Glad PUBLIC "glad/include")
# ImGui
add_compile_definitions(IMGUI_IMPL_OPENGL_LOADER_GLAD=1)
set(IMGUI_SOURCES
"imgui-master/imgui.cpp"
"imgui-master/imgui_demo.cpp"
"imgui-master/imgui_draw.cpp"
"imgui-master/imgui_widgets.cpp"
"imgui-master/examples/imgui_impl_glfw.cpp"
"imgui-master/examples/imgui_impl_opengl3.cpp"
)
set(IMGUI_HEADERS
"imgui-master/imconfig.h"
"imgui-master/imgui.h"
"imgui-master/imgui_internal.h"
"imgui-master/imstb_rectpack.h"
"imgui-master/imstb_textedit.h"
"imgui-master/imstb_truetype.h"
"imgui-master/examples/imgui_impl_glfw.h"
"imgui-master/examples/imgui_impl_opengl3.h"
)
add_library(
ImGui STATIC
${IMGUI_SOURCES}
${IMGUI_HEADERS}
)
target_include_directories(ImGui PUBLIC "imgui-master" "glfw-master/include" "glad/include")
CMakeLists.txt(沙盒)
project(Sandbox)
find_package(OpenGL REQUIRED)
add_executable(sandbox main.cpp)
# OpenGL
target_include_directories(Sandbox PUBLIC ${OPENGL_INCLUDE_DIR})
target_include_directories(Sandbox PUBLIC external)
# Glfw
target_include_directories(Sandbox PUBLIC "../3rd_party/glfw-master/include")
# Link libs
target_link_libraries(Sandbox PUBLIC
${OPENGL_LIBRARIES}
"../3rd_party/glfw-master/src/Debug/glfw3"
Glad
ImGui
glm_static
)
这段代码可以正常运行,但是结果并不符合我的预期。首先,我知道它可能有点丑陋,也许有更好的方法来处理包含和源路径,但更大的问题是项目结构。 例如,在将其构建为 MS VS Studio 时,我有三个解决方案。
./framework.sln
./sandbox/sandbox.sln
./3rd_party/glfw-master/glfw.sln
而 glad、glm 和 imgui 是 sandbox.sln 的一部分。
我想要的是一个解决方案,其中包含两个子解决方案 sandbox 和 3rd_party,它们也都有所有库的子解决方案或项目。
那么这是否可能呢?如果可以,我该如何使用 cmake 创建这样的结构?