tags:

views:

48

answers:

2

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 runs 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);
}
A: 

sorry, mistake:

./main: symbol lookup error: ./testb.so: undefined symbol: **printa**
renyufei
Please edit your question, rather than leaving answers which aren't answers.
crazyscot
A: 

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

renyufei