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

目录变化

相关推荐
郝学胜_神的一滴16 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天1 天前
C++ 基础入门完全指南
c++
用户805533698033 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK3 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境4 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境4 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴5 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境7 天前
C++ 的Eigen 库全解析
c++
卷无止境7 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴7 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake