Linux简单调用so库及Makefile用法

1.test.h
#include 
//函数指针
typedef int (*ADD)(int,int);

2.test.c
#include 
int add(int a, int b){
  printf(".PHONY 测试!\n");
  return (a + b);
}

3.测试程序main.c
#include 
#include 
#include 
#include "test.h"

int main(){
  void *handle=dlopen("./libtest.so",RTLD_LAZY);  
  ADD add=NULL;
  
  *(void **)(&add)=dlsym(handle,"add");  
  int result=add(2,5);
  
  printf("a + b = %d\n",result);
  return 0;
}


4.Makefile
#$@--目标文件(main), $^--所有的依赖文件(main.c), $<--第一个依赖文件.
CC := gcc
.PHONY:all clean
# test
SOURCE  := $(wildcard *.c) #把*.c赋值给SOURCE
OBJS    := $(patsubst %.c,%.o,$(SOURCE)) #把*.c替换成*.o

all: libtest.so main
libtest.so: test.o
	@echo $@ $^ "11111"
	$(CC) -shared -o $@ $^  #编译-shared生成so共享库

test.o: test.c
	@echo $@ $^ "2222"
	$(CC) -c -fPIC -o $@ $^ #-c只编译不链接; PIC: Position Independent Code	

main: main.c
	@echo $@ $^ "3333"
	$(CC) -o $@ $^ -ldl #不需指定libtest.so进行编译,执行会在指定目录加载so
	./main
	#ldd main
clean:
	rm  *.so *.o main


 

你可能感兴趣的:(linux,基础知识)