리눅스에서 공유 라이브러리 만들기
리눅스에서 공유 라이브러리를 만들 때 가장 중요한 것은 소스 파일을 컴파일할 때 -fpic
또는 -fPIC
플래그를 쓰는 것이다. -fpic
플래그가 더 작은 파일을 만들어 주지만 전역 오프셋 테이블(global offset table, GOT)의 크기가 머신의 최대 크기를 넘어 가면 오류가 난다. 이 경우 -fPIC
플래그를 쓰면 되는데 좀 더 큰 파일을 생성한다. 이 두 플래그 중 하나를 사용하지 않으면 다음과 같은 오류가 난다.
/usr/lib64/gcc/x86_64-slackware-linux/5.5.0/../../../../x86_64-slackware-linux/bin/ld: oaprintf.o: relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC oaprintf.o: error adding symbols: Bad value collect2: error: ld returned 1 exit status Makefile:10: recipe for target 'libaprintf.so' failed make: *** [libaprintf.so] Error 1
다음은 공유 라이브러리를 만드는 간단한 과정이다.
cc -Wall -Werror -fpic -o this.o this.c
cc -Wall -Werror -fpic -o that.o that.c
cc -shared -o libtest.so this.o that.o
Libaprintf의 Makefile
을 살펴 보면 다음과 같다.
CFLAGS=-Wall -Werror -fpic
LDFLAGS=-shared
all: libaprintf.so test
clean:
$(RM) -f *.o test
libaprintf.so: count.o oaprintf.o aprintf.o faprintf.o saprintf.o snaprintf.o
$(CC) $(LDFLAGS) -o $@ $^
test: test.c
$(CC) $(CFLAGS) -o $@ $< -L. -laprintf
# 개별의 *.o 파일이 필요할 때마다 같은 파일명의 *.c 파일을 다음과 같이 컴파일한다.
%.o: %.c
$(CC) $(CFLAGS) -c $<
참고문헌
- Shared libraries with GCC on Linux
- Shared Libraries
- 공유 라이브러리 (살짝 어색한 번역투)