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来指定生成

目录变化

相关推荐
艾莉丝努力练剑2 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
旖旎夜光2 小时前
面试题 01.02: 判定是否互为字符重排 (哈希表) —— 题解
c++·笔记·学习·算法·哈希表
白小飞不会飞3 小时前
【AUTOSAR】CP SOME/IP-TP
c++·嵌入式硬件·网络协议·车载系统·autosar
ShineWinsu14 小时前
对于Qt:信号量(QSemaphore)的解析
c++·qt·面试·笔试·客户端·线程安全·信号量
星恒随风14 小时前
从0实现C++ AI大模型接入SDK(八):SessionManager会话管理——智能指针、原子操作、线程安全与懒加载机制
linux·服务器·开发语言·c++·人工智能
白小飞不会飞19 小时前
【AUTOSAR】CP System Template(9):一份完整配置与排错清单
c++·嵌入式硬件·车载系统·autosar
白小飞不会飞20 小时前
【AUTOSAR】CP System Template(8):抽取与扁平化
c++·嵌入式硬件·车载系统·autosar
apcipot_rain1 天前
C++开发 面试 1Day速通
开发语言·c++·面试
星恒随风1 天前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
鱼很腾apoc1 天前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习