- mymath.h:
#ifndef _MYMATH_H
#define _MYMATH_H
int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
#endif
- mymath.c:
#include "mymath.h"
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
- main.c
#include <stdio.h>
#include <unistd.h>
#include "mymath.h"
int main()
{
int a = 20;
int b = 5;
printf("add(%d, %d)=%d\n", a, b, add(a, b));
printf("sub(%d, %d)=%d\n", a, b, sub(a, b));
printf("mul(%d, %d)=%d\n", a, b, mul(a, b));
printf("div(%d, %d)=%d\n", a, b, div(a, b));
return 0;
}
- makefile:
SRC = mymath.c
OBJS = $(SRC:%.c=%.o)
LIB = libmymath.so
SONAME = $(LIB)
CC = gcc -std=gnu99 -fPIC
CFLAGS = -g -O2 -Wall -Wextra
LDFLAGS = -Wl,-soname,$(SONAME)
DEPLIBS =
SHARED = -shared
.c.o:
$(CC) $(CFLAGS) -o $@ -c $<
@echo "Compile $< to $@ OK"
all:
@make libmymath
libmymath: $(OBJS)
$(CC) -o $(LIB) $(SHARED) $(LDFLAGS) $(OBJS) $(DEPLIBS)
clean:
@rm -f $(OBJS)
@rm -f $(LIB)
.PHONY: all clean
make
gcc -o main main.c -lmymath -L.
ldd main
readelf -d libmymath.so
修改makefile中SONAME = libmymath.1.so
重新運行程序
錯誤查看