编写CMakeLists.txt文件进行C++程序的cmake编译

  CMake是一种跨平台的编译工具,可以方便的管理C++代码。通过cmake命令,可以将CMakeLists.txt文件中的定义转换成编译所需的makefile文件,再用make的命令编译可生成可执行文件。

一、单独编译main.cpp文件

  首先在空的test文件夹里建立build文件夹、CMakeLists.txt文件、main.cpp文件。

mkdir build
touch CMakeLists.txt
touch main.cpp

在这里插入图片描述
  在main.cpp文件夹中输入如下语句打印"hello main.cpp"

#include <iostream>

int main()
{
    std::cout<<"hello main.cpp"<<std::endl;
    return 0;
}

  在终端中,可以输入g++ ./main.cpp -o ./main,可以对main.cpp进行编译,生成一个名为main的可执行文件。
在这里插入图片描述

那如何用CMakeLists.txt来实现单文件的编译呢?

CMakeLists.txt中只需要输入三行语句

#1.指定cmake版本
cmake_minimum_required(VERSION 2.8)
#2.project name,指定项目的名字
project(CPP)
#3.生成的可执行文件名为main
add_executable(main main.cpp)

然后进入到build文件夹,分别输入如下两条指令进行编译,生成可执行文件main

cmake ..
make
运行可执行文件:
./main
在这里插入图片描述


二、编译一组cpp和h文件

  如果我们有自定义的源文件(hello.cpp)和自定义的头文件(hello.h),该如何编写CMakeLists.txt呢?我们先来定义好源文件和头文件,分别在test文件夹下建立include文件夹,里面建立一个hello.h文件,建在test下建立一个src文件夹,里面建立一个hello.cpp文件:
在这里插入图片描述

test.h如下:

#pragma once
#include <iostream>
void printHello();

test.cpp如下:

#include "hello.h"

void printHello()
{
    std::cout<<"hello C++"<<std::endl;
}

main.cpp改为如下:

#include <iostream>
#include "hello.h"

int main()
{
    printHello();
    std::cout<<"hello main.cpp"<<std::endl;
    return 0;
}

此时CMakeLists.txt改为6步:

#1.指定cmake版本
cmake_minimum_required(VERSION 2.8)

#2.project name,指定项目的名字
project(CPP)

#3.头文件目录
include_directories(include)

#4.设置库文件名称为hello
add_library(hello src/hello.cpp)

#5.生成可执行文件
add_executable(main main.cpp)

#6.将库文件链接到可执行文件
target_link_libraries(main hello)

来到build文件夹下,执行:
cmake ..
make
./main

在这里插入图片描述


三、编译多组cpp和h文件

  那如果有多个源文件(hello2.cpp)和多个头文件(hello2.h),我们如何链接呢?我们还是分别在includesrc目录下新建hello2.cpphello2.h
在这里插入图片描述

hello2.h如下:

#pragma once
#include <iostream>
void printHello2();

hello2.cpp如下:

#include "hello2.h"

void printHello2()
{
    std::cout<<"hello2 C++"<<std::endl;
}

main.cpp修改如下:

#include <iostream>
#include "hello.h"
#include "hello2.h"
int main()
{
    printHello();
    printHello2();
    std::cout<<"hello main.cpp"<<std::endl;
    return 0;
}

CMakeLists.txt只需要增加一步(第4步),将src文件夹下的文件统一链接到可执行文件。

#1.指定cmake版本
cmake_minimum_required(VERSION 2.8)

#2.project name,指定项目的名字
project(CPP)

#3.头文件目录
include_directories(include)

#4.源文件目录,将其值赋给DIR_SRCS
aux_source_directory(src DIR_SRCS)

#5.设置库文件名称为hello
add_library(hello ${DIR_SRCS})

#6.生成可执行文件
add_executable(main main.cpp)

#7.将库文件链接到可执行文件
target_link_libraries(main hello)

build文件夹下,执行:
cmake ..
make
./main

在这里插入图片描述


  • 9
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI Chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值