在Ubuntu系统中,使用GCC编译动态库(共享库)的步骤如下:
hello.c的文件,内容如下:#include <stdio.h>
void hello() {
printf("Hello from the shared library!\n");
}
.o文件)。在这个例子中,我们将生成一个名为hello.o的目标文件:gcc -c -fPIC hello.c -o hello.o
这里,-c选项表示只编译不链接,-fPIC选项表示生成位置无关代码(Position Independent Code),这对于创建共享库是必需的。
libhello.so的共享库:gcc -shared hello.o -o libhello.so
这里,-shared选项表示生成共享库。
现在,你已经成功创建了一个名为libhello.so的动态库。你可以在其他程序中使用-L和-l选项来链接这个库。例如,创建一个名为main.c的文件,内容如下:
#include <stdio.h>
void hello(); // 声明外部函数
int main() {
hello();
return 0;
}
然后,使用以下命令编译main.c文件,并链接到libhello.so动态库:
gcc main.c -L. -lhello -o main
这里,-L.选项表示在当前目录下查找库文件,-lhello选项表示链接名为libhello.so的库。
最后,运行生成的可执行文件:
./main
输出结果应为:
Hello from the shared library!