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

目录变化

相关推荐
lengxuenong1 分钟前
枚举及其优化学习手册
c++·学习·算法·青少年编程
Benny_Tang25 分钟前
P9527 [JOIST 2022] 洒水器 / Sprinkler 题解
c++·算法
垆边人似月.1 小时前
华为机考题:最小代价爬楼梯
c语言·c++
可涵不会debug1 小时前
C++ std::bind 实战教程:线程池、回调场景全覆盖
linux·开发语言·c++
垆边人似月.2 小时前
华为机考题:二叉树的最大路径和
c语言·c++
2601_962218612 小时前
深入理解C++中的thread_local线程局部变量的应用
开发语言·c++
无名猿3 小时前
C++ lambda 捕获列表详解:值捕获、引用捕获、初始化捕获与悬垂引用
c++·现代c++·语法基础·踩坑记录
lengxuenong4 小时前
枚举例题分析
c++·算法·青少年编程
繁华的地方不一定留下你的脚印4 小时前
C++线程如何安全停止与唤醒:std::jthread、stop_token与condition_variable
开发语言·c++
沫璃染墨4 小时前
《从零入门Linux系统篇(五十一):线程篇·四——pthread线程库详解:从线程创建到终止与分离》
linux·运维·服务器·开发语言·c++·系统架构·线程