头文件
/*
@ 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 __cpluscplus
extern "C"
{
#endif
int 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 __cpluscplus
extern "C"
{
#endif
int 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 = gcc
CFLAGS =
LDFLAGS = -shared -fPIC
INC = -I.
LIBS =
DLL = libcalc.so
TESTOBJS = test.o
OBJS = $(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_RegisterClasses
0000152c A __bss_start
w __cxa_finalize
w __gmon_start__
0000152c A _edata
00001534 A _end
00000414 T _fini
00000280 T _init
000003bc T add
000003c7 T sub
可以看到 add sub 两个接口类型为T,说明接口成功导出
编译测试程序
$ make test
执行测试程序
$ ./test
test add [ 1+2 = 3]
test sub [ 1-2 = -1]