开发者

dynamic lib can't find static lib

env: gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9)

app: Bin(main) calls dynamic lib(testb.so), and testb.so contains a static lib(libtesta.a).

file list: main.c test.h a.c b.c

then compile as:

gcc -o testa.o -c a.c

ar -r libtesta.a testa.o

gcc -shared -fPIC -o testb.so b.c

gcc -o main main.c -L. -ltesta -ldl

then compile success, but r开发者_JS百科uns an error:

./main: symbol lookup error: ./testb.so: undefined symbol: print

code as follows:

test.h

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dlfcn.h>



int printa(const char *msg);

int printb(const char *msg);

a.c

#include "test.h"

int
printa(const char *msg)
{
    printf("\tin printa\n");
    printf("\t%s\n", msg);
}

b.c

#include "test.h"

int
printb(const char *msg)
{
    printf("in printb\n");
    printa("called by printb\n");
    printf("%s\n", msg);
}

main.c

#include "test.h"


int
main(int argc, char **argv)
{
    void    *handle;
    int    (*dfn)(const char *);

    printf("before dlopen\n");

    handle = dlopen("./testb.so", RTLD_LOCAL | RTLD_LAZY);
    printf("after dlopen\n");
    if (handle == NULL) {
        printf("dlopen fail: [%d][%s][%s]\n", \
            errno, strerror(errno), dlerror());
        exit(EXIT_FAILURE);
    }

    printf("before dlsym\n");
    dfn = dlsym(handle, "printb");
    printf("after dlsym\n");
    if (dfn == NULL) {
        printf("dlsym fail: [%d][%s][%s]\n", \
            errno, strerror(errno), dlerror());
        exit(EXIT_FAILURE);
    }

    printf("before dfn\n");

    dfn("printb func\n");

    printf("after dfn\n");

    exit(EXIT_SUCCESS);
}


if I add -fPIC to gcc while compile the static, then it works well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜