C++多个文件生成动态库实战

一 编写test1.cpp

#include <iostream>
using namespace std;
void f1(int age)
{
    cout << "this is libtest1.so: " << age << endl;
}

二 编写test2.cpp

#include <iostream>
using namespace std;
void f2(int age)
{
    cout << "this is libtest2.so: " << age << endl;
}

三 编写main.cpp

extern void f1(int age);   //声明要使用的函数
extern void f2(int age);   //声明要使用的函数
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    f1(65);
    f2(66);
    cout << "bye" << endl;
    
    return 0;
}

四 生成动态库文件libtest1.so

[root@localhost test]# g++ test1.cpp test2.cpp -fPIC -shared -o libtest1.so
[root@localhost test]# ll
total 24
-rwxr-xr-x. 1 root root 8832 Apr 14 11:32 libtest1.so
-rw-r--r--. 1 root root  239 Mar 24 13:11 main.cpp
-rw-r--r--. 1 root root  117 Mar 24 13:11 test1.cpp
-rw-r--r--. 1 root root  117 Mar 24 13:11 test2.cpp

五 添加路径到/etc/ld.so.conf

[root@localhost test]# pwd
/root/C++/ch10/10.4/test
[root@localhost test]# vi /etc/ld.so.conf
[root@localhost test]# cat /etc/ld.so.conf
include ld.so.conf.d/*.conf
/root/C++/ch10/10.4/test/

六 执行ldconfig命令并编译运行

[root@localhost test]# g++ main.cpp -L. -ltest1 -o main
[root@localhost test]# ldconfig
[root@localhost test]# ./main
this is libtest1.so: 65
this is libtest2.so: 66
bye

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值