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

目录变化

相关推荐
旖旎夜光24 分钟前
【C++ 基础入门】C++多态(下):单/多继承虚表、多态补充与 21 道高频题
开发语言·c++·笔记·学习
apcipot_rain11 小时前
C++转Java日记(03)
java·开发语言·c++
布莱克60511 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_67811 小时前
深挖C++:类和对象(中)
开发语言·c++
D e re k ZH14 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
xiaoye-duck15 小时前
《C++ 项目:手写大模型接入 SDK》Ollama接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
zaizai100715 小时前
【Effective Modern C++】学习第一章
c++
Fruiticecake16 小时前
C 程序员速通现代 C++(一):lambda、std::function、移动语义与智能指针
c语言·c++
青少儿编程课堂16 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
坤坤子吖19 小时前
Linux网络编程:TCP服务器的多进程与多线程实现
linux·服务器·开发语言·网络·c++·笔记·学习