cmake编译带有库函数的C++文件(多目录编译)

174 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情。 写文章不易,阅读之前请给我点个赞吧~

我们通过的登录一个远程的linux服务器,来尝试编译一个稍微复杂一点的demo 通过命令 cat /etc/os-release 查看当前系统版本等信息,这里使用的是 "CentOS Linux"

image.png

一、把 上节的内容 在linux上操作一下

创建相关文件

touch helloworld.cpp
touch CMakeLists.txt
mkdir build

访问相关文件

vim helloworld.cpp

输入模式 i,然后shift ins粘贴以下代码

#include <stdio.h>

int main(int argc, char* argv[])
{
        printf("HelloWorld\n");
        say_pi();
        return 0;
}

esc 然后 :wq 保存后退出。

vim CMakeLists.txt,然后shift ins粘贴以下代码

cmake_minimum_required (VERSION 3.10)

# set the project name
project (helloworld)

# add the executable
aux_source_directory(. src_list)
add_executable(hello ${src_list})

二、新增一些库函数

2.1 修改根目录的 CMakeLists.txt

修改 /cmake_projects/demo1/CMakeLists.txt

cmake_minimum_required (VERSION 2.8)

# set the project name
PROJECT(helloworld)

# 添加libs子目录
add_subdirectory(libs) #新增

# 查找当前目录下的所有源文件,并将名称保存到 src_list 变量
aux_source_directory(. src_list)

# add the executable
add_executable(hello ${src_list})

#添加链接库
target_link_libraries(hello test)#新增

【注意】

  • 其中 add_subdirectory(libs) 添加子目录libs,其作用是在执行 cmake 的时候,就会到子目录,也就是这里的 libs 文件夹下执行其中的 CMakeLists.txt 。
  • target_link_libraries( helloworld PUBLIC test ) 把 helloworld 和 test 这两个可执行文件用一个动态链接库,把它们链接。可执行文件 helloworld 需要连接一个名为 test 的链接库 。

你需要提前准备 libs 分支的以下文件

image.png

2.2 修改子目录下的 CMakeLists.txt

新增 /cmake_projects/demo1/libs/CMakeLists.txt

# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_TEST_SRCS 变量
aux_source_directory(. DIR_TEST_SRCS)

# 生成链接库
add_library(test ${DIR_TEST_SRCS})

2.3 库函数文件

cmake_projects/demo1/libs/test.h

#include <stdio.h>
#define PI 3.1415926

cmake_projects/demo1/libs/test.cpp

#include <stdio.h>
#include "test.h"

void say_pi(void)
{
        printf("PI = %f \n",PI);
}

三、编译

3.1 cmake ../

进到 build 目录 cmake ../ 可以看到当前目录下已经生成了下面这些文件,可以看到已经生成了 Makefile,可以使用cat命令看看里面晦涩难懂的内容。

image.png

3.2 cmake --build .

3.3 make

四、其他

如果出现编译错误,可以尝试更新cmake的版本,这里更新到 3.23 版

# 下载 3.23 版
wget  https://cmake.org/files/v3.23/cmake-3.23.0-rc1.tar.gz
# 解压
tar -zxvf  cmake-3.23.0-rc1.tar.gz
# 编译
cd cmake-3.23.0-rc1
./configure
# 安装
make 
make install
# 确认
/usr/local/bin/cmake --version
# 建立软连接
ln -s /usr/local/bin/cmake /usr/bin/
# 查看版本
cmake --version