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

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

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

编写CMakeLists.txt文件进行C++程序的编译
  • 一、单独编译main.cpp文件
  • 二、编译一组cpp和h文件
  • 三、编译多组cpp和h文件

一、单独编译main.cpp文件

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

mkdir build
touch CMakeLists.txt
touch main.cpp


  在main.cpp文件夹中输入如下语句打印"hello main.cpp"

#include 

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 
void printHello();

test.cpp如下:

#include "hello.h"

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

main.cpp改为如下:

#include 
#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 
void printHello2();

hello2.cpp如下:

#include "hello2.h"

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

main.cpp修改如下:

#include 
#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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/717979.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存