_ZNote_转载_Mac_如何在MacOSX中制作和使用dylib_简单实例
转自(http://qvb3d.iteye.com/blog/1176920)
1, 首先构建一个函数库
//add.c int add (int a,int a) { return a + b; } int axb(int a,int b) { return a*b; }
2,编译函数库
gcc -c add.c -o add.o
ar rcs libadd.a add.o //Linux
gcc add.o -dynamiclib -current_version 1.0 -o libadd.dylib //macOS
3,编辑testadd.c
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int main(int argc,char *argv[]) { int a,b; a=10; b=9; int c; c=add(a,b); printf("%d\n",c); return 1; }
4,编译 testadd.c
gcc testadd.c -o testadd -L. -ladd
运行 ./testadd 可得到输出结果 19
5,编辑dladd.c 这个是为了查看函数库在库中的地址的
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int main(int argc,char *argv[]) { int *ab; void *h=dlopen("./libadd.dylib",RTLD_LAZY); ab=dlsym(h,"add"); printf("add=address is 0x %x\n",ab); dlclose(h); return 1; }
6,编译 dladd.c
gcc dladd.c -o dladd -ldl
运行 ./dladd 的结果: add = 内存地址.
从〇开始,回到〇
posted on 2017-06-28 14:42 ZhangDezhi 阅读(576) 评论(0) 编辑 收藏 举报