GNU >> C/C++

-rdynamic


參考資訊:
1. what-exactly-does-rdynamic-do-and-when-exactly-is-it-needed

-rdynamic: This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table

dl.c

#include <stdio.h>

void out(const char*);

void hello(void)
{
    out("hello, world!\n");
}

P.S. 由於export all symbols,因此,可以在share library中呼叫out()

main.c

#include <dlfcn.h>
#include <stdio.h>

typedef void hello(void);

void out(const char *buf)
{
    printf("%s", buf);
}

int main(int argc, char **argv)
{
    void *h = dlopen("./hello.so", RTLD_NOW);
    hello *p = dlsym(h, "hello");
    p();
    dlclose(h);
    return 0;
}

編譯、執行(沒有-rdynamic)

$ gcc dl.c -shared -fPIC -o hello.so
$ gcc main.c -o main -ldl
$ ./main
    ERR: ./hello.so: undefined symbol: out

編譯、執行(加上-rdynamic)

$ gcc dl.c -shared -fPIC -o hello.so
$ gcc main.c -o main -ldl -rdynamic
$ ./main
    hello, world!


返回上一頁