现在有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 |
//base/base.h #ifndef BASE_H
#define BASE_H void hello_base(); #endif //BASE_H
//base/base.cpp #include "base.h"
#include <stdio.h> void hello_base()
{
printf("hello base\n");
}
#base/CMakeLists.txt
cmake_minimum_required(VERSION 3.12) set(HEADER_LIST base.h)
set(SOURCE_LIST base.cpp) file(COPY ${HEADER_LIST} DESTINATION ".") add_library(base ${HEADER_LIST} ${SOURCE_LIST})
- file(COPY ${HEADER_LIST} DESTINATION ".")
主要是为了把头文件做为一个编译输出,方便下面的使用
service 模块
- service.h - service.cpp - CMakeLists.txt |
//service/service.h #ifndef SERVICE_H
#define SERVICE_H
#include "base.h" //用来测试main模块是否能找到base.h,正常尽量在源文件内包含头文件 void hello_service(); #endif //SERVICE_H
//service/service.cpp #include "service.h"
#include <stdio.h> void hello_service()
{
printf("hello service\n");
hello_base();
}
#service/CMakeLists.txt
cmake_minimum_required(VERSION 3.12) set(SOURCE_LIST service.cpp)
set(HEADER_LIST service.h) add_subdirectory(${CMAKE_SOURCE_DIR}/../base base.output)
include_directories(base.output) file(COPY ${HEADER_LIST} DESTINATION ".") add_library(service ${HEADER_LIST} ${SOURCE_LIST}) add_dependencies(service base)
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 |
//main/main.cpp #include "service.h" int main(int argc, const char* argv[])
{
hello_service();
return ;
}
#main/CMakeLists.txt
cmake_minimum_required(VERSION 3.12) project(main)
set(SOURCE_LIST main.cpp) add_subdirectory(${CMAKE_SOURCE_DIR}/../service service.output) file(GLOB_RECURSE INC_PATH *.h)
foreach(DIR ${INC_PATH})
STRING(REGEX REPLACE "/[a-z,A-Z,0-9,_,.]+$" "" dirName ${DIR})
include_directories(${dirName})
endforeach() add_executable(main ${SOURCE_LIST} ${HEADER_LIST}) add_dependencies(main service)
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的依赖里,暂时没有想到更好的方法
赞成为第一个赞同者