// mymath.h #include <math.h> extern int sum(int n1, int n2); |
// mymath.c #include "mymath.h" int sum(int n1, int n2) { return n1 + n2; } |
//main.c #include "mymath.h" #include <stdio.h> #include <dlfcn.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { void *handle = NULL; int(*result)(int, int); handle = dlopen("./libmymath.so", RTLD_NOW); if(!handle){ printf("fail to dlopen, %s\\n", dlerror()); return 0; } result = dlsym(handle, "sum"); if(dlerror()!=NULL){ printf("fail to dlsym, %s\n", dlerror()); return 0; } printf("10+20=%d\n", result(10,20)); dlclose(handle); return 0; } |
4. so 파일 생성
gcc -c mymath.c -fPIC
gcc -shared -o libmymath.so mymath.o
5. 실행 파일 생성 및 실행
gcc -o main main.c -ldl
./main
./main : error while loading shared libraries : libmymath.so : cannot open shared object file : No such file or directory
만약, 실행파일이 위와 같이 올바르게 실행되지 않을 경우에는
LD_LIBRARY_PATH 환경변수에 libmymath.so 가 있는 디렉토리를 명시해주거나,
/usr/lib/ 디렉토리 안에 libmymath.so 파일을 복사하면 된다.
출처: https://m.blog.naver.com/PostView.nhn?blogId=myunani&logNo=90173215015&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F