關鍵
# 指定 main 可執行檔案的包含目錄,包括根目錄${CMAKE_SOURCE_DIR} ( folder1 和 folder2 目錄) target_include_directories(main PRIVATE ${CMAKE_SOURCE_DIR})
功能
A和B類編譯成庫
A類呼叫B類
C主函式 呼叫A類和B類
C主函式 和 A,B在同一個目錄
總 CMakeLists.txt
cmake_minimum_required(VERSION 3.10) project(MyProject) # Set C++ standard #set(CMAKE_CXX_STANDARD 11) #set(CMAKE_CXX_STANDARD_REQUIRED ON) # Add subdirectories add_subdirectory(folder1) add_subdirectory(folder2) add_subdirectory(folder3)
資料夾3 CMakeLists.txt
# 建立 folder3 的可執行檔案(假設 C.cpp 是主函式) add_executable(main C.cpp) message(STATUS "專案根目錄: " ${CMAKE_SOURCE_DIR}) # 指定 main 可執行檔案的包含目錄,包括根目錄${CMAKE_SOURCE_DIR} ( folder1 和 folder2 目錄) target_include_directories(main PRIVATE ${CMAKE_SOURCE_DIR}) # 連結 main 與 folder1_lib 和 folder2_lib(假設 C.cpp 使用了 folder1 中的 A 和 folder2 中的 B) target_link_libraries(main PRIVATE folder1_lib folder2_lib)
C.cpp
/* //#include "../folder1/A.h" //#include "../folder2/B.h" target_include_directories 指令並指定了包含目錄後, 確實可以直接使用 #include "folder1/A.h" 和 #include "folder2/B.h", 而不必使用相對路徑 ../folder1/A.h 和 ../folder2/B.h。 這是因為 target_include_directories 指定了編譯器在編譯時查詢標頭檔案的路徑, 使得編譯器可以在指定的包含目錄中找到這些標頭檔案。 */ #include "folder1/A.h" #include "folder2/B.h" class C { public: void run(); }; void C::run() { A a; B b; a.doSomething(); b.performAction(); } int main() { C c; c.run(); return 0; }
CMakeLists.txt
# 定義庫目標 add_library(folder2_lib STATIC B.cpp B.h) # 設定庫的公共標頭檔案路徑 target_include_directories(folder2_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
B.h
#ifndef B_H #define B_H #include <iostream> class B { public: void performAction(); }; #endif // B_H
B.cpp
#include "B.h" void B::performAction() { std::cout << "Class B is performing an action." << std::endl; }
CMakeLists.txt
# 定義庫目標 add_library(folder1_lib A.cpp A.h) #將 folder1 的當前源目錄包含為公共目錄,以便其他目標可以訪問到 A.h 檔案。# 連結 folder2 庫與 folder1 庫 target_include_directories(folder1_lib PUBLIC ${CMAKE_SOURCE_DIR}) target_link_libraries(folder1_lib PUBLIC folder2_lib)
A.h
#ifndef A_H #define A_H #include <iostream> //#include "../folder2/B.h" #include "folder2/B.h" class A { public: void doSomething(); }; #endif // A_H
A.cpp
#include "A.h" void A::doSomething() { std::cout << "Class A is doing something." << std::endl; B b; b.performAction(); }