在Ubuntu下使用GCC编译动态库(共享库)的步骤如下:
首先,你需要编写一些C或C++源文件。例如,假设你有两个源文件 libexample.c 和 helper.c。
libexample.c
#include <stdio.h>
void example_function() {
printf("This is an example function.\n");
}
helper.c
#include <stdio.h>
void helper_function() {
printf("This is a helper function.\n");
}
为了使其他程序能够使用你的动态库,你需要创建一个头文件 libexample.h。
libexample.h
#ifndef LIBEXAMPLE_H
#define LIBEXAMPLE_H
void example_function();
void helper_function();
#endif // LIBEXAMPLE_H
使用GCC编译每个源文件生成目标文件(.o 文件)。
gcc -c libexample.c -o libexample.o
gcc -c helper.c -o helper.o
使用GCC将目标文件链接成动态库(.so 文件)。通常,动态库的名称以 lib 开头,以 .so 结尾。
gcc -shared -o libexample.so libexample.o helper.o
你可以编写一个测试程序来使用这个动态库。
test.c
#include <stdio.h>
#include "libexample.h"
int main() {
example_function();
helper_function();
return 0;
}
编译测试程序并链接动态库:
gcc -o test test.c -L. -lexample
确保动态库在运行时可以被找到。你可以将动态库复制到 /usr/lib 或 /usr/local/lib,或者设置 LD_LIBRARY_PATH 环境变量。
export LD_LIBRARY_PATH=.
./test
如果你不再需要中间文件,可以删除它们。
rm libexample.o helper.o libexample.so test
通过这些步骤,你可以在Ubuntu下成功编译和使用动态库。