CMake二、带文件多文件编译

方法一

tool/tool.h

cpp 复制代码
#include <iostream>

using namespace std;

class tool
{
public:
    tool();
    ~tool();
    void work();
};

tool/tool.cpp

cpp 复制代码
#include "tool.h"
tool::tool()
{
    cout<<"tool 构造"<<endl;
}
tool::~tool()
{
    cout<<"tool 析够"<<endl;
}
void tool::work()
{
    cout<<"work 干活"<<endl;
}

main.cpp

cpp 复制代码
#include <iostream>
#include "tool/tool.h"
using namespace std;

int main()
{
    tool t;
    t.work();
    cout<<"main已调用"<<endl;
    return 0;
} 

CMakeLists.txt

cpp 复制代码
cmake_minimum_required(VERSION 3.5)
#设置最低cmake版本
project(main_tool)
#设置目标工程名字
add_executable(main_tool main.cpp tool/tool.cpp )
#生成可执行程序

方法二

对CMakeLists.txt做修改

cpp 复制代码
cmake_minimum_required(VERSION 3.5)
#设置最低cmake版本
project(main_tool)
#设置目标工程名字
aux_source_directory(. CPPLIST1)
#获取当前目录下的文件,赋值到CPP------LIST1
aux_source_directory(./tool CPPLIST2)
#获取./tool目录下的文件,赋值到CPP------LIST2
add_executable(main_tool ${CPPLIST1} ${CPPLIST2})
#生成可执行程序

方法三

将tool文件生成.a

tool/CMakeLists.txt

cpp 复制代码
aux_source_directory(. tool_file)
#查找当前目录下的tool相关文件
 
add_library(tool1lib ${tool_file})
#将他们编译为一个叫tool1lib的文件

CMakeLists.txt

cpp 复制代码
cmake_minimum_required(VERSION 3.5)
#设置最低cmake版本
project(main_tool)
#设置目标工程名字

aux_source_directory(. CPP_LIST)  
#搜索当前目录下的所有cpp文件
add_subdirectory(tool)           
#将tool文件夹加入子目录,这样他就可以去tool文件夹中查找编译
#[请进入 tool子目录,找到那里的 CMakeLists.txt文件,然后执行它。
简单说,就是包含另一个 CMakeLists.txt 文件,实现模块化构建。]
add_executable(out_tool ${CPP_LIST}) 
#生成目标文件
 
target_link_libraries(out_tool tool1lib)
#添加链接库,其库的名字由tool1文件夹中的CMakeLists.txt来指定生成

目录变化

相关推荐
炸膛坦客8 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎8 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
Henry Zhu1239 小时前
C++中的特殊成员函数与智能指针
c++
_wyt00111 小时前
多重背包问题详解
c++·背包dp
Ljwuhe12 小时前
C++——多态
开发语言·c++
越甲八千12 小时前
STL stack为何没有迭代器
c++
从零开始的代码生活_14 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸14 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
GIS阵地15 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
王维同学15 小时前
[原创][Windows C++]LSA 认证、安全与通知包的注册表枚举
c++·windows·安全