Chinaunix首页 | 论坛 | 博客
  • 博客访问: 968961
  • 博文数量: 200
  • 博客积分: 5011
  • 博客等级: 大校
  • 技术积分: 2479
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 15:07
文章分类

全部博文(200)

文章存档

2009年(12)

2008年(190)

我的朋友

分类:

2008-08-09 23:40:06

转载自:
 
我的程序大体框架是这样的:

我把dll.cpp用-shared选项编译成dll.so,在dll.cpp当中引用了静态库libA.a当中的符号。然后dll.so是在main当中用dlopen打开的。

编译和链接都没有问题,但是在运行的时候会报如下的错误:

./dll.so: undefined symbol: _ZN1AC1EiSegmentation fault

所以我猜想可能是我在动态库中引用了静态库中的符号的缘故(参见Makefile中g++ -shared -L. -lA -o dll.so dll.cpp)。
请大家帮我看看怎么办呢? 应该加上什么参数呢?

各个文件文件的代码如下:

makefile
All:    main dll

main:    static dll main.cpp
    g++ -ldl -o main main.cpp

dll:    dll.cpp static
    g++ -shared -L. -lA -o dll.so dll.cpp

static:    A.cpp
    g++ -c A.cpp
    ar rc libA.a A.o


A.h
class A
{
public:
    A(int a);            
};

A.cpp
#include "A.h"
#include <iostream>

using namespace std;

A::A(int a)
{
    cout << "in A.A() " << a << endl;   
}

dll.cpp
#include <string>
#include <iostream>
#include "A.h"

using namespace std;

template<int F>
class dll
{
public:
    A *a;
public:
    dll(int id)
    {
        a = new A(id);
        cout << id << " " << F << endl;
    }
};

template class dll<4>;

extern "C"
{
    void maker(int id)
    {
        new dll<4>(id);
    }
}

main.cpp
#include <dlfcn.h>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    char *p;   
    void *lib;
    lib = dlopen("./dll.so", RTLD_LAZY);
    if (lib == NULL)
    {
        cout << "NULL" << endl;
        p = dlerror();
        cout << p << endl;
    }
    else
        cout << std::hex << lib << endl;
    typedef void (*FUNC) (int);
    FUNC sym = (FUNC) dlsym(lib, "maker");
    sym(3);


    return 0;
}
GCC官方文档里讲

QUOTE:
-llibrary
-l library
    Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)

    It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.

是不是顺序问题
g++ -shared -L. -lA -o dll.so dll.cpp
在win下挂驴呢,LZ自己试试调整顺序吧

 
CODE:
g++ -shared  dll.cpp -L. -lA -o dll.so

最终结论是:连接的库,一定要在使用该库的目标被连接之后,如果目标A使用了库B中的函数,那么目标A应该首先被连接,然后是库B,否则有些函数的实现可能不会被连接近来。
阅读(962) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~