项目结构如下
CMakeLists清单
最外层的主CMakeLists
cmake_minimum_required(VERSION 3.17)
project(cmakeMulPackage)
set(CMAKE_CXX_STANDARD 11)
#添加一个子目录并构建该子目录
add_subdirectory(proj1)
add_subdirectory(proj2)
#定义头文件路径
include_directories(proj1/include proj2/include)
#生成可执行exe
add_executable(cmakeMulPackage app/src/main.cpp)
#目标依赖要使用的库的路径
link_directories(./lib)
#指定链接给目标依赖要使用的库
target_link_libraries(cmakeMulPackage
MyProj1
MyProj2)
proj1的CMakeLists
#定义头文件路径
include_directories(./include)
#同时生成lib与DLL
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ../lib) #DLL生成路径
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ../lib) #lib生成路径
set(CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ../pdb) #pdb生成路径
#把目录src下面的所有文件作为变量存储
aux_source_directory(./src SOURCES)
#生成库
add_library(MyProj1 STATIC ${SOURCES})
proj2的CMakeLists
#定义头文件路径
include_directories(./include)
#同时生成lib与DLL
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ../lib) #DLL生成路径
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ../lib) #lib生成路径
set(CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ../pdb) #pdb生成路径
#把目录src下面的所有文件作为变量存储
aux_source_directory(./src SOURCES)
#生成库
add_library(MyProj2 STATIC ${SOURCES})
项目代码
main.cpp
#include <iostream>
#include "hello.h"
#include "world.h"
int main() {
std::cout << "Hello, World!" << std::endl;
hello();
world();
return 0;
}
proj1/hello.h
#pragma execution_character_set("utf-8")
void hello(void);
proj1/hello.cpp
#include <cstdio>
#include "hello.h"
void hello()
{
printf("proj1. 111111111\n");
}
proj2/world.h
#pragma execution_character_set("utf-8")
void world(void);
proj2/world.cpp
#include <cstdio>
#include "world.h"
void world()
{
printf("proj2. 22222222\n");
}