cmake 遞歸依賴


現在有3個模塊:main、service、base,main依賴service的service.h、service依賴base的base.h,怎么寫CMakeList.txt避免main直接耦合base

- main

- service

- base

 

base模塊

 

- base.h

- base.cpp

- CMakeLists.txt

 

1 //base/base.h
2 
3 #ifndef BASE_H
4 #define BASE_H
5 
6 void hello_base();
7 
8 #endif //BASE_H

 

1 //base/base.cpp
2 
3 #include "base.h"
4 #include <stdio.h>
5 
6 void hello_base()
7 {
8     printf("hello base\n");
9 }

 

 1 #base/CMakeLists.txt  2 
 3 cmake_minimum_required(VERSION 3.12)
 4 
 5 set(HEADER_LIST base.h)
 6 set(SOURCE_LIST base.cpp)
 7 
 8 file(COPY ${HEADER_LIST} DESTINATION  ".")
 9 
10 add_library(base ${HEADER_LIST} ${SOURCE_LIST})
  •  file(COPY ${HEADER_LIST} DESTINATION  ".")

主要是為了把頭文件做為一個編譯輸出,方便下面的使用

service 模塊

- service.h

- service.cpp

- CMakeLists.txt

 

1 //service/service.h
2 
3 #ifndef SERVICE_H 
4 #define SERVICE_H 
5 #include "base.h" //用來測試main模塊是否能找到base.h,正常盡量在源文件內包含頭文件 6 7 void hello_service(); 8 9 #endif //SERVICE_H

 

 1 //service/service.cpp
 2 
 3 #include "service.h"
 4 #include <stdio.h>
 5 
 6 void hello_service()
 7 {
 8     printf("hello service\n");
 9     hello_base();
10 }

 

 1 #service/CMakeLists.txt  2 
 3 cmake_minimum_required(VERSION 3.12)
 4 
 5 set(SOURCE_LIST service.cpp)
 6 set(HEADER_LIST service.h)
 7 
 8 add_subdirectory(${CMAKE_SOURCE_DIR}/../base base.output)
 9 include_directories(base.output)
10 
11 file(COPY ${HEADER_LIST} DESTINATION  ".")
12 
13 add_library(service ${HEADER_LIST} ${SOURCE_LIST})
14 
15 add_dependencies(service base)
16 target_link_libraries(service base)
  • add_subdirectory(${CMAKE_SOURCE_DIR}/../base base.output)

將base模塊的輸出base.h、libbase.a放到當前目錄的base.output下

main 模塊

- main.cpp

- CMakeLists.txt

1 //main/main.cpp
2 
3 #include "service.h"
4 
5 int main(int argc, const char* argv[])
6 {
7     hello_service();
8     return 0;
9 }

 

 1 #main/CMakeLists.txt  2 
 3 cmake_minimum_required(VERSION 3.12)
 4 
 5 project(main)
 6 set(SOURCE_LIST main.cpp)
 7 
 8 add_subdirectory(${CMAKE_SOURCE_DIR}/../service service.output)
 9 
10 file(GLOB_RECURSE INC_PATH *.h)
11 foreach(DIR ${INC_PATH})
12     STRING(REGEX REPLACE "/[a-z,A-Z,0-9,_,.]+$" "" dirName ${DIR})
13     include_directories(${dirName})
14 endforeach()
15 
16 add_executable(main ${SOURCE_LIST} ${HEADER_LIST})
17 
18 add_dependencies(main service)
19 target_link_libraries(main service)
  • add_subdirectory(${CMAKE_SOURCE_DIR}/../service service.output)

將service的輸出放到service.output,而base的輸出自動到了service.output/base.output下

  • foreach(DIR ${INC_PATH}) .....

遍歷所有包含頭文件的目錄(output目錄)添加到main的依賴里,暫時沒有想到更好的方法

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM