我会做关于创建共享库的过程中一个不起眼的审查。
让我们首先创建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