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的依赖里,暂时没有想到更好的方法

 

 

posted @ 2019-04-04 16:44  Tianrks  阅读(2138)  评论(1编辑  收藏  举报