在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
環境變量來告訴系統在哪里查找動態鏈接庫。
現在,當你運行程序時,它應該能夠成功調用動態鏈接庫中的函數并輸出相應的消息。