回调函数,C语言编程中很常见,下面呈现一种常用的编程方式
头文件
/*
@ 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 __cplusplus
extern "C"
{
#endif
struct _CALC_FUNCLIST {
int (*add)(int a, int b);
int (*sub)(int a, int b);
};
typedef struct _CALC_FUNCLIST CALC_FUNCLIST;
int dowork(CALC_FUNCLIST *pFuncList, int a, int b);
#ifdef __cplusplus
}
#endif
#endif
源文件
/*
@ File Name: calc.c
@ Author: hw
@ Mail: feiyelove@163.com
@ Created Time: 2015-07-01 14:39:26
*/
#include "calc.h"
int dowork(CALC_FUNCLIST *pFuncList, int a, int b)
{
pFuncList->add(a, b);
pFuncList->sub(a, b);
return 0;
}
测试程序
/*
@ 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 add(int a, int b)
{
printf("%d + %d = %d \n", a, b, a+b);
return a + b;
}
int sub(int a, int b)
{
printf("%d - %d = %d \n", a, b, a-b);
return a - b;
}
static CALC_FUNCLIST s_funcList =
{
add,
sub,
};
int main()
{
dowork(&s_funcList, 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
编译动态库
$ make
编译测试程序
$ make test
执行测试程序
$ ./test
1 + 2 = 3
1 - 2 = -1
可以看到,test程序调用到了动态库中的dowork接口,dowrok接口回调了test程序中的add sub接口