编译库文件随笔记录
// mylib.h #ifndef _MYLIB_H_ #define _MYLIB_H_ #include <stdio.h> void print();#endif // _MYLIB_H_
// mylib.c #include "mylib.h" void print() { printf("this is a line text\n"); }
静态库文件编译:
gcc -c -o mylib.o mylib.c ar rcs libstatic.a mylib.o
静态库测试代码:
// test.c #include "mylib.h" #include <dlfcn.h> int main() { print(); }
静态库链接:
gcc -o test test.c -L. -lstatic
运行:
动态库测试代码:
// test.c #include "mylib.h" #include <dlfcn.h> int main() { const char* error; void* handle = dlopen("./libshared.so", RTLD_LAZY); error = dlerror(); if (error) { printf("%s\n", error); return -1; } void (*p)() = (void (*)())dlsym(handle, "print"); error = dlerror(); if (error) { printf("\n"); printf("%s\n", error); return -1; } p(); dlclose(handle); }
生成动态库文件:
gcc -fPIC -shared -o libshared.so mylib.c
编译测试:
gcc -o test test.c -ldl
其中-ldl为dlopen、dlsym等调用库函数的库。
运行:
浙公网安备 33010602011771号