编译动态链接库,windows,linux,mac平台各不相同,从文件上来说,windows下是dll,linux下是so,mac下是dylib;命令上也会有区别,windows下用cl,linux下用gcc但是参数是-fPIC -shared,而在mac下则是gcc -dynamiclib -o libxxx.dylib xxx.c。
这里介绍在mac下手动编译动态库示例:
准备hello.h
#ifndef SO_H
#define SO_H
int add(int a,int b);
void hello(char* str,char* res);
#endif
hello.c
#include <string.h>
#include "hello.h"
int add(int a,int b){
return a + b + 1;
}
void hello(char* str,char* res){
strcat(str,"world.");
strcpy(res,str);
}
开始编译动态库:
gcc -dynamiclib -o libhello.dylib hello.c
编译完成,在目录下会生成一个文件libhello.dylib
编写测试程序,调用动态链接库:
test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "