使用另一个共享库创建共享库

时间:2009-11-17 09:39:22

标签: linux gcc linker shared-libraries

我有一个共享库“libwiston.so”。我正在使用它来创建另一个名为“libAnimation.so”的共享库,它将被另一个项目使用。现在,第二个库“libAnimation.so”无法正确用于测试代码。所以我怀疑第二个lib“libAnimation.so”的创建是对的。用于创建此lib的gcc命令是

 g++ -g -shared -Wl,-soname,libwiston.so -o libAnimation.so $(objs) -lc". 

有人遇到过这个问题吗?

2 个答案:

答案 0 :(得分:3)

这看起来像一个奇怪的链接线 - 您正在创建libAnimation.so,但其内部DT_SONAME名称为libwiston.so

我不认为你想做什么。您是否要将libAnimation.solibwiston.so-lwiston)相关联?

g++ -g -shared -o libAnimation.so $(objs) -lc -lwiston

我认为将您的构建包装在automake / autoconf中更容易,并依赖libtool来创建正确的共享库。

答案 1 :(得分:0)

我会对创建共享库的过程进行简单的回顾。

让我们从创建 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);
};

此代码可以使用以下代码编译:{{1​​}}

现在我们实现第二个名为 libAnimation.so 的共享库,它调用第一个库导出的函数。

g++ libwiston.cpp -o libwiston.so -shared

和标题:

/* 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); };

最后,我们创建了一个小应用程序来测试libAnimation。

g++ libAnimation.cpp -o libAnimation.so -shared -L. -lwiston

并使用:/* file demo.cpp * Implementation of the test application. */ #include "libAnimation.h" int main() { std::string msg = "hello stackoverflow!"; call_wiston(msg); }

进行编译

有一个名为 nm 的有趣工具,您可以使用它来列出共享库导出的符号。使用这些示例,您可以执行以下命令来检查符号:

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
相关问题