欢迎来到代码驿站!

Linux

当前位置:首页 > 服务器 > Linux

动态库调用静态库示例讲解

时间:2021-06-19 08:17:12|栏目:Linux|点击:

生成动态库: 需要的目标文件得用-fPIC选项生成.

而静态库所需的目标文件可以不用-fPIC选项.

例:

复制代码 代码如下:

/////// static.h

void static_print();

///////static.cpp

#include <iostream>

#include "static.h"

void static_print() {

     std::cout<<"This is static_print function"<<std::endl;

}

////// shared.h

void shared_print();

////// shared.cpp

#include <iostream>

#include "shared.h"

#include "static.h"

void shared_print() {

       std::cout<<"This is shared_print function";

        static_print();

}

////////test.cpp

   #include "share.h"

int main()
{
       shared_print();
       return 0;
   }

方法一:

静态库的.o文件也用-fPIC生成. 生成动态库时把静态库加入.

 生成应用程序时只加载动态库

复制代码 代码如下:

 g++ -c -fPIC static.cpp // 生成static.o

 ar -r libstatic.a static.o // 生成静态库libstatic.a

 g++ -c -fPIC shared.cpp // 生成shared.o

 g++ -shared shared.o -lstatic -o libshared.so   // 生成动态库libshared.so 注: -shared是g++的选项,与shared.o无关. -lstatic选项把libstatic.a的函数加入动态库中.

 g++ test.cpp -lshared -o test.exe // link libshared.so 到test.exe中.
 

方法二:

 静态库的.o文件不用-fPIC生成. 生成动态库时不加表态库.

生成应用程序时加载动态库和静态库.

复制代码 代码如下:

 g++ -c static.cpp // 生成static.o

 ar -r libstatic.a static.o // 生成静态库libstatic.a

 g++ -c -fPIC shared.cpp // 生成shared.o

 g++ -shared shared.o -o libshared.so // 生成动态库libshared.so 注: -shared是g++的选项,与shared.o无关. 这时如果加-lstatic. error:relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC

 g++ test.cpp -lshared -lstatic -o test.exe // link libshared.so 到test.exe中.
 

两种方法的不同之处在于static_print的实际代码一个在.so中.一个在最后test.exe文件中. 个人觉得第一种方法更好, 因为动态库应该看成一个可以独立运行的程序.

上一篇:使用Samba在Linux服务器上搭建共享文件服务的方法

栏    目:Linux

下一篇:Linux的认识存在的一些误区

本文标题:动态库调用静态库示例讲解

本文地址:http://www.codeinn.net/misctech/144479.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有