一、準備cpp和h文件
- 創建test.cpp
在cpp
中定義相加的函數funcAdd,給出函數的細節代碼
#include <iostream>
using namespace std;int funcAdd(int x, int y)
{return x+y;
}
- 創建test.h
在h
中聲明定義的函數,不需要任何細節
#ifndef __TEST__
#define __TEST__
using namespace std;int funcAdd(int x, int y);#endif
二、生成.so文件
- 生成.so文件
將test.cpp和test.h放在同一目錄下,在該目錄打開終端,運行以下代碼
g++ -fpic -shared -o libtest.so test.cpp
此時會生成libtest.so
文件,包括了test中的所有函數,已經自動讀取了頭文件。
- 將.so文件復制到路徑
/usr/lib
下
sudo cp libtest.so /usr/lib
// 刪除文件
// sudo rm -rf /usr/lib/libtest.so
三、生成測試文件并運行
- 創建測試文件main.cpp
#include "test.h"
#include <iostream>
using namespace std;int main() {cout<<funcAdd(2,3);return 0;
}
- 編譯main.cpp并鏈接.so生成可執行文件main
g++ -o main main.cpp -L. -ltest
這一步生成了可執行文件main,其中main.cpp代碼中調用了.so文件中的函數
- 運行可執行文件main
./main
參考鏈接
https://blog.csdn.net/mu_xing_/article/details/116978567