cmake 遞歸依賴

如今有3個模塊:main、service、base,main依賴service的service.h、service依賴base的base.h,怎麼寫CMakeList.txt避免main直接耦合base測試

- mainui

- servicespa

- basecode

 

base模塊

 

- base.hblog

- base.cppci

- CMakeLists.txtget

 

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  ".")

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

service 模塊

- service.h編譯

- service.cpptable

- 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的依賴裏,暫時沒有想到更好的方法

 

 

成爲第一個贊同者
相關文章
相關標籤/搜索