2016-05-23 105 views
3

所以我想了解我的一個C++項目出了什麼問題。基本上,項目1工作正常,一切都很好。在該項目的主頭文件我有CMake - 如何組織依賴

#include "spdlog/spdlog.h" 

而且我spdlog作爲項目1項目1。另外一個子項目在我的CMake我有include_directories(spdlog/include)。現在,我正在構建項目2,該項目取決於項目1,並將其作爲子項目。但是,當我嘗試包含spdlog時,它不允許我並且希望我完整填寫../project1/spdlog/include/spdlog.h。什麼是正確的方式來組織這種依賴關係,幷包括標題?

+0

這是不是那麼必須'../ PROJECT1/spdlog /包含/ spdlog/spdlog.h'?無論如何,'include_directories()'的範圍可能會非常棘手。所以我想你可以通過讓'spdlog'傳播它自己的include目錄來解決這個問題,如果你的'spdlog'子目錄有它自己的'CMakeLists.txt'文件''target_include_directories(spdlog PUBLIC「include」)'。 – Florian

+0

我會保持spdlog作爲第三方依賴。然後嘗試找到它的標題和庫。 – usr1234567

+0

@ usr1234567你能解釋一下怎麼做更詳細的說明嗎?它實際上是一個只有標題的庫。對不起,如果這是一個愚蠢的問題,我對C++和CMake很陌生,試圖以正確的方式去做。 –

回答

0

你應該尋找現代化的cmake資源。在現代cmake風格中,您可以爲spdlog創建一個導入目標,然後您可以在其他地方使用它。

讓我們假設在以下結構

external/spdlog 
external/CMakeLists.txt 
project1/CMakeLists.txt 
project2/CMakeLists.txt 
CMakeLists.txt 

external/CMakeLists.txt你寫

## add the imported library which is 
## an INTERFACE (ie header only) 
## IMPORTED (ie third party - no compilation necessary) 
## GLOBAL (you can reference it from everywhere 
##   even if the target is not in the same scope 
##   which is the case for project1 and project2 because 
##   the spdlog target is not in their parent folder) 
add_library(spdlog INTERFACE IMPORTED GLOBAL) 
## set the include directory which is to be associated with this target 
## and which will be inherited by all targets which use 
## target_link_libraries(<target> spdlog) 
target_include_directories(spdlog INTERFACE spdlog/include) 
CMakeLists.txt你寫你的解決方案配置(例如)

project(mysolution) 
add_subdirectory(external) 
add_subdirectory(project1) 
add_subdirectory(project2) 

項目中的根

CMakeLists.txt你現在可以使用/您在external

PROJECT1創建的目標的CMakeLists.txt

add_library(project1 ${Sources}) 
## this will set the include directories configured in the spdlog target (library) 
## and also ensure that targets depending on target1 will have access to spdlog 
## (if PUBLIC were changed to PRIVATE then you could only use spdlog in 
## project1 and dependeing targets like project2 would not 
## inherit the include directories from spdlog it wouldn't 
target_link_libraries(project1 PUBLIC spdlog) 

項目2 /的CMakeLists.txt

add_library(project2 ${Sources}) 
## this will link project1 which in return also links spdlog 
## so that now project2 also has the include directories (because it was inherited) 
## also targets depending on project2 will inherit everything from project1 
## and spdlog because of the PUBLIC option 
target_link_libraries(project2 PUBLIC project1) 

來源:

[0] https://cmake.org/cmake/help/v3.9/command/add_library.html

[1] https://cmake.org/cmake/help/v3.9/command/target_link_libraries.html?highlight=target_link_libraries

[2] http://thetoeb.de/2016/08/30/modern-cmake-presentation/(參見呈現開始於幻燈片20)