一 编写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