程式語言 - GNU - CFLAGS -rdynamic



參考資訊:
https://stackoverflow.com/questions/36692315/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

share.c

1
2
3
4
5
6
7
8
#include <stdio.h>
 
void out(const char*);
 
void hello(void)
{
    out("hello, world!\n");
}

P.S. 由於Export All Symbols,因此,可以在Share Library中呼叫out()

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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 share.c -shared -fPIC -o share.so
$ gcc main.c -o main -ldl
$ ./main
    ERR: ./share.so: undefined symbol: out

編譯、執行(加上-rdynamic)

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