2010년 2월 19일 금요일

g++ 사용시 동적라이브러리 빌드문제 해결

동적라이브러리를 사용해서 프로그램 개발시 gcc로 사용할 때는 문제가 없지만 g++을 사용하면서 문제가 발생하기 시작했다.

 

< 문제 1 >

  • 오류: "dlsym"함수에서 발생하는 "invalid conversion"
  • 해결1:
    • 선언: "int (*func)(char *)"
    • Type casting: "func = (int (*)(char *))dlsym(dl_handle, method);"
  • 해결2:
    • 선언: "void (*fn)(char *, int *);"
    • Type casting: "*(void **)(&fn) = dlsym(dl_handle, "hello1");"

 

< 문제 2 >

  • 오류: 컴파일시 "undefined reference to `dlopen',..." 발생
  • 해결: 컴파일 옵션에 "-ldl" 추가 "g++ -o testdll testdll.cpp -lc -ldl"

 

< 문제 3 >

  • 오류: 컴파일도 잘 끝나고 실행하니... "libhello.so: undefined symbol: hello" 오류 발생
  • 해결: "libhello.cpp"에 extern "C" 선언을 추가
#include "stdio.h"
#include "string.h"

extern "C"
{
	int hello(char *msg);
}

int hello(char *msg)
{
	printf("%s\n", msg);

	return strlen(msg);
}

test_dll.sh

# Build library
if [ -f libhello.o ]; then rm libhello.o
fi
g++ -Wall -fPIC -c libhello.cpp

if [ -f libhello.so ]; then rm libhello.so
fi
g++ -shared -lc -o libhello.so libhello.o

# Build test program
if [ -f testdll.o ]; then rm testdll.o
fi
g++ -Wall -o testdll testdll.cpp -ldl

# Run test program
./testdll

 

그외

  • "nm <object>": 명령어로 오브젝트의 심볼 확인
  • "file filename"

 

참고자료:

  1. toidinamaiblog
  2. 윈도우에서 유닉스로 이식하기, Part 1: C/C++ 이식 (한글)
  3. Static, Shared Dynamic and Loadable Linux Libraries
  4. Writing and Using Libraries

댓글 없음:

댓글 쓰기