CMake在静态库中链接动态库

heheda@linux:~/Linux/multi-v3$ tree
.
├── calc
│   ├── add.cpp
│   ├── CMakeLists.txt
│   ├── div.cpp
│   ├── mult.cpp
│   └── sub.cpp
├── CMakeLists.txt
├── include
│   ├── calc.h
│   └── sort.h
├── sort
│   ├── CMakeLists.txt
│   ├── insert.cpp
│   └── select.cpp
└── test
    ├── CMakeLists.txt
    └── sort.cpp

4 directories, 13 files
heheda@linux:~/Linux/multi-v3$ 

嵌套的CMake-CSDN博客 在这篇博客的基础上,删除test1文件夹,将test2文件夹 修改其文件名为test

一、在静态库中链接静态库 

  • 修改sort.cpp,包含calc.h文件,调用add函数
  • sort.cpp 
#include "sort.h"
#include <iostream>
#include "calc.h"
using namespace std;
int  main()
{
    int number1 = add(1,23);
    cout<<"调用calc库 中的add函数,那么1 + 23 = "<<number1<<endl;
    int a[10] = {8,1,9,7,2,4,5,6,10,3};
    insert(a,10);
    cout<<"插入排序结果:";
    print(a,10);
    select(a, 10);
    cout << "选择排序结果: ";
    print1(a, 10);
}

  • calc文件夹中的CMakeLists.txt(改动)
cmake_minimum_required(VERSION 3.10)
project(calc)

# 搜索源文件
aux_source_directory(./ SRC)
include_directories(${HEADPATH}) # 头文件路径 HEADPATH

set(LIBRARY_OUTPUT_PATH ${LIBPATH}) # 库生成的路径 LIBPATH
add_library(${CALCLIB} SHARED ${SRC}) # 生成动态库
  • sort文件夹中的CMakeLists.txt(改动:在静态库中链接动态库)
cmake_minimum_required(VERSION 3.10)
project(sort)

# 搜索源文件
aux_source_directory(./ SRC)
# 头文件路径 HEADPATH
include_directories(${HEADPATH}) 

set(LIBRARY_OUTPUT_PATH ${LIBPATH}) # 库生成的路径 LIBPATH

link_directories(${LIBPATH})
add_library(${SORTLIB} STATIC  ${SRC}) # 生成静态库

# 链接calc动态库
target_link_libraries(${SORTLIB} ${CALCLIB})
  •  test文件夹中的CMakeLists.txt(不做改动)
cmake_minimum_required(VERSION 3.10)
project(test2)

aux_source_directory(./ SRC)
include_directories(${HEADPATH})

set(EXECUTABLE_OUTPUT_PATH ${EXECPATH})

# 包含静态库路径
link_directories(${LIBPATH})
# 链接静态库, sort为静态库的名字
link_libraries(${SORTLIB})
add_executable(${APPNAME2} ${SRC}) 
  • 项目根目录中的CMakeLists.txt(改动) 
cmake_minimum_required(VERSION 3.10)
project(test)
# 定义变量

# 库生成的路径
set(LIBPATH ${PROJECT_SOURCE_DIR}/lib)

# 可执行程序的存储目录(测试程序生成的路径)
set(EXECPATH ${PROJECT_SOURCE_DIR}/bin)

# 头文件路径
set(HEADPATH ${PROJECT_SOURCE_DIR}/include)

# 库文件的名字
set(CALCLIB calc)
set(SORTLIB sort)

# 可执行程序的名字
set(APPNAME1 app1)
set(APPNAME2 app2)

# 给当前节点添加子目录
add_subdirectory(calc)
add_subdirectory(sort)
add_subdirectory(test)