Ubuntu--(5)Linux下C++编译生成自定义静态库/动态库

本文介绍了如何在Ubuntu Linux环境下使用C++编译生成自定义的静态库(libtest.a)和动态库(libtest.so)。通过编写test.h文件,然后进行编译和链接步骤,详细阐述了生成及调用这两个库的过程,包括main函数的编写和测试运行。

编译生成静态库:

1.编写CPP文件test.h
#include <iostream>

using namespace std;

class ADD_SUB{
public:
    int add(int a, int b){
        cout << "a + b = " << a + b << endl;
        return a + b;
    }

    int sub(int a, int b){
        cout << "a - b = " << a - b << endl;
        return a - b;
    }
};
2.编译
g++ -o test.out -c test.h
3.生成
ar -cr libtest.a test.out
4.调用libtest.a的main函数如下:
#include <iostream>
#include "test.h"

using namespace std;

void main(){
    ADD_SUB as;
    as.add(1,3);
    as.sub(1,3);
}
5.编译
main.cpp: g++ main.cpp
6.运行:
./a.out

C++生成动态库

1.编写如生成静态库一样的test.h文件。
2.编译
g++ -shared -fPIC -o libtest.so  test.h
3.调用libtest.so的main函数与静态库一样

4.编译

g++ -o main.out main.cpp
5.运行测试
./main.out
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值