linux下动态库(一)

来源:互联网 发布:淘宝怎样找货源 编辑:程序博客网 时间:2024/06/13 13:19

头文件

/*  @ File Name: calc.h  @ Author: hw  @ Mail: feiyelove@163.com  @ Created Time: 2015-07-01 14:42:00*/#ifndef _CALC_H_#define _CALC_H_#ifdef __cpluscplusextern "C"{#endifint add(int a, int b);int sub(int a, int b);#ifdef __cpluscplus}#endif#endif

实现体

/*  @ File Name: calc.c  @ Author: hw  @ Mail: feiyelove@163.com  @ Created Time: 2015-07-01 14:39:26*/#include "calc.h"#ifdef __cpluscplusextern "C"{#endifint add(int a, int b){        return a + b;}int sub(int a, int b){        return a - b;}#ifdef __cpluscplus}#endif

测试程序

/*  @ File Name: test.c  @ Author: hw  @ Mail: feiyelove@163.com  @ Created Time: 2015-07-01 17:50:16*/#include <stdio.h>#include <stdlib.h>#include "calc.h"int main(){        printf("test add [ 1+2 = %d]\n", add(1,2));        printf("test sub [ 1-2 = %d]\n", sub(1,2));        return 0;}

Makefile

CC      = gccCFLAGS  =LDFLAGS = -shared -fPICINC     = -I.LIBS    =DLL     = libcalc.soTESTOBJS        = test.oOBJS    = $(filter-out $(TESTOBJS),$(patsubst %.c,%.o,$(wildcard *.c)))$(DLL):$(OBJS)        $(CC) $(LDFLAGS) -o $(DLL) $(OBJS)$(OBJS):%.o:%.c        $(CC) $(CFLAGS) $(INC) -c $< -o $@$(TESTOBJS):%.o:%.c        $(CC) $(CFLAGS) $(INC) -c $< -o $@test:$(TESTOBJS)        $(CC) -o test $(TESTOBJS) $(DLL)clean:        rm -f *.o        rm -f $(DLL) test

上述就是一个简单的linux动态库实现

编译动态库

$ make

查看动态库导出符号

$ nm -D libcalc.so          w _Jv_RegisterClasses0000152c A __bss_start         w __cxa_finalize         w __gmon_start__0000152c A _edata00001534 A _end00000414 T _fini00000280 T _init000003bc T add000003c7 T sub

可以看到 add sub 两个接口类型为T,说明接口成功导出

编译测试程序

$ make test

执行测试程序

$ ./test test add [ 1+2 = 3]test sub [ 1-2 = -1]
0 0
原创粉丝点击