add.h 文件
int add(int a, int b);
add.c文件
#include “add.h”
int add(int a, int b)
{
return a + b;
}
test.c文件
#include
#include “../include/add.h”
int main()
{
int a=1;
int b=2;
int c;
c=add(a,b);
printf(“1+2=%d\n”,c);
return 0;
}
编译源文件
CC=gcc
cflags = -I../include
sources = \
../src/add.c
debug: $(srouces)
$(CC) -c -fPIC -ggdb $(cflags) $(sources)
release: $(sources)
$(CC) -c -Os -fPIC $(cflags) $(sources)
生成静态库
ar -r libAdd.a *.o
生成动态库
gcc -shared -o libAdd.so *.o
调用静态库
CC=gcc
cflags = -I../include
sources = \
test.c
testStatic: $(sources)
$(CC) -o test $(sources) -lm -L ../lib -lAdd -static
调用动态库
CC=gcc
cflags = -I../include
sources = \
test.c
testDynamic: $(sources)
$(CC) -o test $(sources) -lm -L ../lib -lAdd
运行时可能找不到动态库
export LD_LIBRARY_PATH=