cmake 创建静态库、创建动态库、进行连接

C++ 使用cmake编译

学习如何创建 静态库、动态库、
学习如何连接现有的 静态库、动态库、

生成静态库示例:

在account_dir目录下:
在这里插入图片描述

Account_.h

#ifndef Account_H
#define Account_H

class Account1
{
private:
    /* data */
public:
    Account1(/* args */);
    ~Account1();
};
#endif // Account_H

Account1.cpp

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

Account1::Account1(/* args */)
{
    std::cout << "构造函数Account::Account()" << std::endl;
}
Account1::~Account1()
{
    std::cout << "析构函数Account::~Account()" << std::endl;
}

CMakeLists.txt

#account_dir/CMakeLists.txt

# 最低版本要求
cmake_minimum_required(VERSION 3.10)

# 项目信息
project(A_001)

# 添加静态库,Linux下会生成libAccount.a
# Account是库名,STATIC表示静态库,SHARED表示动态库,后面是源文件
# 静态库:lib库名.a 动态库:lib库名.os
add_library(A_001 STATIC Account1.cpp Account_.h)

依次输入命令:

cmake -S . -B build
cmake --build build

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
libA_001.a 是生成好的静态文件,其他暂时无用,先删除。

链接静态库

在这里插入图片描述
使用刚生成的静态库,进行连接。

CMakeLists.txt

# test_account/CMakeLists.txt

# 最低版本要求
cmake_minimum_required(VERSION 3.10)

# 当前项目名称
project(A_002)

# 添加执行文件
add_executable(A_002 test_account.cpp)


# 指定目标包含的头文件目录
target_include_directories(A_002 PUBLIC "../account_dir")
# 添加库文件目录,如果不添加,找不到库文件
target_link_directories(A_002 PUBLIC "../account_dir/build")
# 指定目标链接的库  静态:lib库名.a、动态:lib库名.os
target_link_libraries(A_002 PRIVATE A_001)

test_account.cpp

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

int main()
{
    Account1 alice_account;
    std::cout << "test Account 的main函数" << std::endl;
    return 0;
}

在test_account路径下,再输一次命令:

cmake -S . -B build
cmake --build build

在这里插入图片描述
查看链接库的详情:

ldd ./build/A_002 
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

默执_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值