linux下编写编译动态库

一,编写动态库源文件

alg.h

 1 #ifndef _ALG_H
 2 #define _ALG_H
 3 
 4 #ifdef __cplusplus
 5 extern "C"{
 6 #endif
 7 #ifndef _ALG_H
 8 #define _ALG_H
 9 
10 #ifdef __cplusplus
11 extern "C"{
12 #endif
13 
14 int     Sum(int a, int b);
15 
16 #ifdef __cplusplus
17 }
18 #endif
19 
20 #endif //_ALG_H
21 ~                                                                                                                                                                               
22 ~  
23 int     Sum(int a, int b);
24 
25 #ifdef __cplusplus
26 }
27 #endif
28 
29 #endif //_ALG_H
30 
31                                                                                                                                                                            
32   

alg.cpp

1 #include "alg.h"
2 
3 int Sum(int a, int b)
4 {
5         return (a+b);
6 }

二,编写测试文件

main.cpp

#include <stdio.h>

#include <dlfcn.h>

typedef int (DLL_FUNC)(int, int);

void testSo( void )
{
        int a=5;
        int b=6;

        void* hInstance = dlopen("./libAlg.so",RTLD_LAZY);

        if(NULL == hInstance)
        {
                printf("dlopen :%s\n",dlerror());
                return;
        }

        DLL_FUNC* lpFunc = (DLL_FUNC*)dlsym(hInstance, "Sum");

        if(NULL == *lpFunc)
        {
                printf("dlsym error:%s\n", dlerror());

                return ;
        }

        int nSum = lpFunc(a, b);

        printf("sum=%d\n", nSum);
}

int main( void )
{
        testSo();
        return 0;
}

三,编译动态库

g++ -c -fPIC alg.cpp

g++ -shared -fPIC -o libAlg.so alg.o 

说明:

fPIC 作用于编译阶段,告诉编译器产生与位置无关代码(Position-Independent Code),
  则产生的代码中,没有绝对地址,全部使用相对地址,故而代码可以被加载器加载到内存的任意
  位置,都可以正确的执行。这正是共享库所要求的,共享库被加载时,在内存的位置不是固定的。

四,编译测试文件

g++ main.cpp -g -ldl -o  main 

五,运行结果

[gxq@localhost ~]$ ./main

sum=11

猜你喜欢

转载自www.cnblogs.com/guoliushui/p/9334523.html
今日推荐