I can load functions from dynamic library with lin

2020-02-07 10:41发布

问题:

I am using gcc/g++ on fedora 116, and my idea is:

c program -> load c++ dynamic library A -> load c++ dynamic library B

The c++ dynamic library B is third-party provided and I can not modify it.

When complinng c++ dynamic library A with linking c++ dynamic library B, A can find symbols in B. But when I load B functions in A code (not linking) using 'dlsym', A tells me

/path/to/B.so: undefined symbol: some_func

=============================

use nm -DC

0000000000014a80 T BinarySearch(int, int*, int)
0000000000007210 T CheckLicense()
0000000000009370 T GetEnd(stCha*, int&, int)
000000000000a970 T IC_Exit()
000000000000a740 T IC_Init(char const*)

the error report:

/path/to/some.so undefined symbol: IC_Init

the code in library A:

IC_API bool (* IC_Init)(const char *);
IC_Init = (IC_API bool (*)(const char *)) dlsym(dl_ic, "IC_Init");
if(IC_Init) {
    printf("function loaded");
}

in library A, it can load library B using dlopen:

void *dl_ic = dlopen(ic_lib_path, RTLD_LAZY);

回答1:

Have you considered name mangling? C++ identifiers are typically "mangled" to incorporate information on their namespace and arguments (which historically helped linkers differentiate overloaded functions). You may want to make the function extern "C" to prevent mangling, or find its mangled name to use with dlsym (e.g. on Linx use nm on an object, or gcc -S -o /dev/tty ... | grep some_func on the source).