簡體   English   中英

如何在我的 cmake 項目中包含另一個 cmake 項目的頭文件?

[英]How to include another cmake project's header files in my cmake project?

我正在嘗試將另一個 CMake 項目包含為我的項目的第三方庫。 問題是我不能包含來自所述庫的標題。

我嘗試使用add_subdirectory函數添加庫,但它似乎不起作用。

這是我的 CMakeLists.txt:

cmake_minimum_required (VERSION 2.6)
project (Cam2ClientCpp)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

include_directories ("${PROJECT_SOURCE_DIR}/restclient-cpp")
add_subdirectory (restclient-cpp)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

add_executable (Cam2ClientCpp main.cpp)
target_link_libraries (Cam2ClientCpp restclient-cpp)

另一個項目的 CMakeLists.txt 在這里: https : //github.com/mrtazz/restclient-cpp/blob/master/CMakeLists.txt

當我運行 make 時,出現以下錯誤:

/Library/Developer/CommandLineTools/usr/bin/c++   -I/Users/nhendy/Development/cam2clientcpp/restclient-cpp  -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk   -std=gnu++11 -o CMakeFiles/Cam2ClientCpp.dir/main.cpp.o -c /Users/nhendy/Development/cam2clientcpp/main.cpp
/Users/nhendy/Development/cam2clientcpp/main.cpp:1:10: fatal error: 'restclient-cpp/connection.h' file not found
#include "restclient-cpp/connection.h"

通常,要使用庫,您必須:

  • 調用add_subdirectory以便解析和解釋此項目的CMakeLists.txt 這使 CMake 知道項目/庫。
  • 庫項目定義了庫的用戶需要知道的包含路徑 ( PUBLIC ),以及內部包含路徑 ( PRIVATE ):
target_include_directories(MyLibrary
  PUBLIC
    include
  PRIVATE
    src
)
  • 庫的用戶只需要引用庫:
target_link_libraries(MyCoolApp
  PRIVATE
    MyLibrary
)

這樣庫導出使用庫所需的路徑,即不是庫的用戶知道如何使用它,而只有庫本身。

我的建議是為圖書館創建一個 PR,並懇請他們使用這種方法。

如果這是不可能的,您可以設置 include_directories。 我的 CMakeLists.txt 看起來像這樣(對你的只有改變的是 include_directories 命令,使用${CMAKE_SOURCE_DIR} ):

cmake_minimum_required (VERSION 2.6)
project (Cam2ClientCpp)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

file(WRITE
  ${CMAKE_BINARY_DIR}/restclient-cpp/include/restclient-cpp/version.h
  "#define RESTCLIENT_VERSION \"0.5.0\"\n"
)

include_directories ("${CMAKE_SOURCE_DIR}/restclient-cpp/include")
include_directories ("${CMAKE_BINARY_DIR}/restclient-cpp/include")
#add_subdirectory (restclient-cpp)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

add_executable (Cam2ClientCpp main.cpp)
target_link_libraries (Cam2ClientCpp restclient-cpp)

我使用以下文件結構進行了測試:

./CMakeLists.txt
./restclient-cpp
./restclient-user
./restclient-user/CMakeLists.txt
./restclient-user/main.cpp
  • restclient-cpp 包含客戶端庫的克隆 repo
  • restclient-user 使用庫的可執行代碼
  • ./CMakeLists.txt 僅包含:
cmake_minimum_required(VERSION 3.10)
add_subdirectory(restclient-cpp)
add_subdirectory(restclient-user)

首先需要單獨編譯第三方庫。 然后鏈接到 CMake 項目中的輸出庫。 查看target_link_libraries

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM