shared library error about “undefined symbol” when using `dlopen`

江枫思渺然 提交于 2021-02-19 07:44:25

问题


First thing first, here's my minimum reproducible program:

CMakeLists.txt:

cmake_minimum_required(VERSION 3.17)
project(untitled4)

set(CMAKE_CXX_STANDARD 17)

add_library(lib1 SHARED lib1.cpp)

add_executable(untitled4 main.cpp)
target_link_libraries(untitled4 PRIVATE dl)

main.cpp:

#include "iostream"
#include <dlfcn.h>
int Test() {
  return 123456;
}
int main() {
  auto* handler = dlopen("/home/liu/source/untitled4/cmake-build-debug/liblib1.so", RTLD_LAZY|RTLD_GLOBAL);
  if (!handler) {
    std::cerr << dlerror();
    exit(1);
  }
}

and lib1.cpp:

#include "iostream"
extern int Test();
class Foo {
 public:
  Foo() {
    std::cout << Test() << std::endl;
  }
};
Foo foo;

now let me explain:

As you can see I defined a function called Test in main.cpp, and I want to the shared library liblib1.so call it when it is loaded.

But when I run the main() function, there's an error log said:

/home/liu/source/untitled4/cmake-build-debug/liblib1.so: undefined symbol: _Z4Testv

I check the symbol by using nm untitled4 |grep Test and the symbol seems exist:

0000000000000b87 t _GLOBAL__sub_I__Z4Testv
0000000000000aea T _Z4Testv

So what did I do wrong? How to fix this?

An important thing to be notice is that in the real case, the build of lib1 and the build of main.cpp are totally separated, the two build don't know each other. But I can make them into one build (very difficult) if this can fix the problem(if there's no other way).

P.S. I tried using extern "C" to wrap around the Test() in both files, but not working, seems not the C/C++ function naming problem.


回答1:


With the addition of the linker option -rdynamic your code does not fail with "undefined symbol".

You can set that with set_target_properties(untitled4 PROPERTIES ENABLE_EXPORTS 1) or target_link_options(untitled4 BEFORE PRIVATE "-rdynamic").

Example:

cmake_minimum_required(VERSION 3.17)
project(untitled4)

set(CMAKE_CXX_STANDARD 17)

add_library(lib1 SHARED lib1.cpp)

add_executable(untitled4 main.cpp)
set_target_properties(untitled4 PROPERTIES ENABLE_EXPORTS 1)

target_link_libraries(untitled4 PRIVATE dl)


来源:https://stackoverflow.com/questions/65005203/shared-library-error-about-undefined-symbol-when-using-dlopen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!