我會做關於創建共享庫的過程中一個不起眼的審查。
讓我們首先創建libwiston.so。首先我們實現我們想要導出的函數,然後在頭上定義它,以便其他程序知道如何調用它。
/* file libwiston.cpp
* Implementation of hello_wiston(), called by libAnimation.so
*/
#include "libwiston.h"
#include <iostream>
int hello_wiston(std::string& msg)
{
std::cout << msg << std::endl;
return 0;
}
和:
/* file libwiston.h
* Exports hello_wiston() as a C symbol.
*/
#include <string>
extern "C" {
int hello_wiston(std::string& msg);
};
該代碼可以編譯:g++ libwiston.cpp -o libwiston.so -shared
現在我們實施第二共享庫,命名爲libAnimation.so調用由第一導出的函數圖書館。
/* file libAnimation.cpp
* Implementation of call_wiston().
* This function is a simple wrapper around hello_wiston().
*/
#include "libAnimation.h"
#include "libwiston.h"
#include <iostream>
int call_wiston(std::string& param)
{
hello_wiston(param);
return 0;
}
和標題:
/* file libAnimation.h
* Exports call_wiston() as a C symbol.
*/
#include <string>
extern "C" {
int call_wiston(std::string& param);
};
與編譯:g++ libAnimation.cpp -o libAnimation.so -shared -L. -lwiston
最後,我們創建一個小的應用程序來測試libAnimation。
/* file demo.cpp
* Implementation of the test application.
*/
#include "libAnimation.h"
int main()
{
std::string msg = "hello stackoverflow!";
call_wiston(msg);
}
並與編譯:g++ demo.cpp -o demo -L. -lAnimation
有一個名爲納米,你可以用它來列出您的共享庫導出的符號一個有趣的工具。通過這些例子,你可以執行以下命令來檢查符號:
nm libAnimation.so | grep call_wiston
輸出:
00000634 t _GLOBAL__I_call_wiston
000005dc T call_wiston
也:
nm libwiston.so | grep hello_wiston
輸出:
0000076c t _GLOBAL__I_hello_wiston
000006fc T hello_wiston
非常感謝,我測試了這個命令,但我會的使用automake/autoconf來創建這個共享庫 – mpouse 2009-11-18 03:34:34
@mpouse檢查一些libwiston的東西在你的Makefile.am中拷貝了libAnimation – 2010-10-26 07:03:06