使用本身封裝的so時遇到了點問題,本着簡便原則決定寫個demo看看,順便記錄下整個過程。測試
1)生成so所需的文件以下:blog
print.hio
#ifndef __print_h__ #define __print_h__ void print(void); #endif
print.cpp編譯
#include <stdio.h> #include "print.h" void print(void) { printf("hello world.\n"); }
bye.hclass
#ifndef __bye_h__ #define __bye_h__ void bye(void); #endif
bye.cpptest
#include <stdio.h> #include "bye.h" void bye(void) { printf("bye bye.\n"); }
midd.hdemo
#ifndef __midd_h__ #define __midd_h__ class Middleware{ public: Middleware(); ~Middleware(); bool data(const char *p); }; #endif
midd.cppdi
#include "print.h" #include "bye.h" #include "midd.h" #include <stdio.h> Middleware::Middleware() { printf("Middleware::Middleware()\n"); } Middleware::~Middleware() { printf("Middleware::~Middleware()\n"); } bool Middleware::data(const char *p) { print(); bye(); return true; }
2)編譯過程文件
g++ -c -fPIC -shared bye.cppco
g++ -c -fPIC -shared print.cpp
g++ -c -fPIC -shared midd.cpp
3)連接過程
g++ -o test.so midd.o print.o bye.o -fPIC -shared
4)動態連接庫的使用
如今寫一個main.cpp來調用so,看看效果
main.cpp
#include "midd.h" int main() { Middleware middleware; middleware.data("xxx"); return 0; }
生成可執行文件:
g++ -o test main.cpp ./test.so
測試:
./test
Middleware::Middleware() hello world. bye bye. Middleware::~Middleware()