多目录工程的CmakeLists.txt编写

本文最后更新于:2022年5月29日 上午

开发一个cmake项目工程,一般会有多级目录,进行代码分类,这里以一个简单的例子介绍一下多目录工程的CmakeLists.txt编写。

功能为print.cpp调用hello.cpp 的hello()函数,main.cpp调用print.cpp 的print()函数。

1、工程目录

image-20210319134001056

一级目录下有整体项目的CMakeLists.txt,子目录也分别有各自的CMakeLists.txt

2、主函数main.cpp

1
2
3
4
5
6
7
8
9
#include <iostream>
#include "print.h"

int main()
{
print();
return 0;
}

3、顶层CMakeLists.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cmake_minimum_required(VERSION 3.1.0)

project(helloxx)

# Add the source in project root directory
aux_source_directory(. DIRSRCS)

# Add header file include directories
include_directories(./ ./hello ./print)

# Add block directories
add_subdirectory(hello)
add_subdirectory(print)

# Target
add_executable(${PROJECT_NAME} ${DIRSRCS})
target_link_libraries(${PROJECT_NAME} hello print)

4、hello文件夹

  • CMakeLists.txt

    1
    2
    aux_source_directory(. DIR_HELLO_SRCS)
    add_library(hello ${DIR_HELLO_SRCS})
  • hello.cpp

    1
    2
    3
    4
    5
    6
    #include "hello.h"

    void hello()
    {
    cout << "hello,";
    }
  • hello.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #ifndef HELLO_H
    #define HELLO_H

    #include <iostream>
    using namespace std;

    void hello();

    #endif

5、print文件夹

  • CMakeLists.txt

    1
    2
    3
    4
    aux_source_directory(./ DIR_PRINT_SRCS)
    add_library(print ${DIR_PRINT_SRCS})

    target_link_libraries(print hello) # 添加链接库,因为需要使用到hello.cpp的hello()函数
  • print.cpp

    1
    2
    3
    4
    5
    6
    7
    #include "print.h"

    void print()
    {
    hello();
    cout << "Cmake" << endl;
    }
  • print.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #ifndef _PRINT_H
    #define _PRINT_H

    #include <iostream>
    #include "hello.h"
    using namespace std;

    void print();

    #endif

多目录工程的CmakeLists.txt编写
https://kevinloongc.github.io/posts/93012594.html
作者
Kevin Loongc
发布于
2021年3月19日
许可协议