在Linux下,使用C++实现动态链接库(DLL)通常涉及以下步骤:
libexample.cpp
的文件,内容如下:// libexample.cpp
#include <iostream>
extern "C" {
void hello_from_dll() {
std::cout << "Hello from the DLL!" << std::endl;
}
}
注意:使用extern "C"
是为了防止C++编译器对函数名进行名称修饰(name mangling),这样其他语言或程序可以更容易地找到并调用这些函数。
g++ -fPIC -c libexample.cpp -o libexample.o
g++ -shared -o libexample.so libexample.o
这里,-fPIC
选项用于生成位置无关代码(Position Independent Code),这是创建共享库所必需的。-c
选项表示只编译不链接,生成目标文件.o
。最后,使用-shared
选项将目标文件链接为动态链接库.so
。
libexample.so
)位于系统的库路径中,或者在编译时指定库路径。然后,在你的程序中包含相应的头文件,并链接动态链接库。例如:// main.cpp
#include <iostream>
// 声明外部函数
extern "C" {
void hello_from_dll();
}
int main() {
hello_from_dll();
return 0;
}
编译并运行程序:
g++ -o main main.cpp -L/path/to/library -lexample
export LD_LIBRARY_PATH=/path/to/library:$LD_LIBRARY_PATH
./main
这里,-L
选项用于指定库路径,-l
选项用于链接库(注意,库名不需要加lib
前缀和.so
后缀)。最后,通过设置LD_LIBRARY_PATH
环境变量来告诉系统在哪里查找动态链接库。
现在,当你运行程序时,它应该能够成功调用动态链接库中的函数并输出相应的消息。