您的位置:首页 > 运维架构 > Linux

linux 下 -------- 创建和调用动态共享库(.so)

2012-10-26 21:38 363 查看
以下print.cpp为要创建的动态共享库

#include<iostream>
#include<vector>

using namespace std;

#ifdef __cplusplus
extern "C"
{
#endif

/*template <typename T>
void print_vector(const vector<T>& v)
{
typename vector<T>::iterator iter = v.begin();

for (; iter != v.end(); ++iter)
cout<<*iter<<" ";

cout<<endl;
}*/

void print_vector(const vector<int>& v)
{
vector<int>::const_iterator iter = v.begin();

for (; iter != v.end(); ++iter)
cout<<*iter<<" ";

cout<<endl;
}

}
#endif




     使用c++创建动态共享库时,要使用如下宏定义,不然可能会找不到相应的符号(由于c++编译时生成symbol名的方式与c有区别)

#ifdef __cplusplus
extern "C"
{
#endif


#ifdef __cplusplus
}
#endif


1. 创建动态共享库

g++  -fPIC -shared -o  libprint.so  print.cpp

2. 使用静态方式使用动态共享库

g++ -g -L./ -lprint -o a.out  main.c

options:

      --------- L:  the .so directory

      -------- l: the .so name

     可以使用LD_LIBRARY_PATH变量指定.so读取的目录 

    

     a. 可执行程序在执行时如何定位共享库文件

当系统加载可执行代码的时候,能够知道其所依赖库的名字,但还需知道其所在的路径

        此时需要系统的动态载入器(linker), 对于elf的可执行程序, 它先搜索elf文件DT_RPATH段的一环境变量LD_LIBRARY_PATH---------- /etc/ld.so.cache文件列表-----------

        /lib, /usr/lib目录找到库

         如 export LD_LIBRARY_PATH=pwd

              将当前文件目录添加为共享目录

    b. 新安装一个库,如何让系统能够找到

如果安装在/lib或/usr/lib下, 那么ld默认能找到, 无需其他操作

        若安装在其他目录, 需将其添加到/etc/ld.so.cache文件中, 步骤如下:

                     1. 编辑/etc/ld.so.conf文件, 加入库目录所在路径

                     2. 运行ldconfig, 该命令会重建/etc/ld.so.cache文件

3. 使用动态方式使用共享库

使用<dlfcn.h>中 的

              dlopen, dlsym, dlclose, dlerror方法, 在代码中动态载入, 这样在编译时就无需添加库选项了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: