dlopen().so无法在剥离的可执行文件中找到符号

时间:2011-05-25 08:53:53

标签: linux dynamic-linking dynamic-loading

我在linux中有一个可执行文件 - exe

此可执行文件中包含一些函数,这些函数在整个代码中使用:

  • sendMsg
  • debugPrint

然后我想动态加载.so,为我的可执行文件提供额外的功能。

在此共享库中,我添加了sendMsgdebugPrint的标头。

我使用dlopen()加载此共享库,并使用dlsym()创建API。

但是,在dlopen()我使用RTLD_NOW在加载时解析所有符号。

它无法说明找不到sendMsg符号。

此符号必须位于可执行文件中,因为sendMsg.c在那里编译。

但是,我的可执行文件被make进程剥离。因此,dlopen找不到符号是有道理的。

我如何解决这种情况?

  • 我可以将共享函数构建到静态库中,并将该静态库链接到exe.so。这会增加代码大小:(
  • 我可以删除exe的剥离,以便找到符号
  • 做一些编译时间链接我不知道的魔法,以便.so知道符号在exe的位置

1 个答案:

答案 0 :(得分:4)

man ld

   -E
   --export-dynamic
   --no-export-dynamic
       When  creating  a  dynamically  linked  executable, using the -E option or the --export-dynamic option causes the linker to add all symbols to the dynamic symbol table.  The
       dynamic symbol table is the set of symbols which are visible from dynamic objects at run time.

       If you do not use either of these options (or use the --no-export-dynamic option to restore the default behavior), the dynamic symbol table will normally contain only  those
       symbols which are referenced by some dynamic object mentioned in the link.

       If  you  use "dlopen" to load a dynamic object which needs to refer back to the symbols defined by the program, rather than some other dynamic object, then you will probably
       need to use this option when linking the program itself.

       You can also use the dynamic list to control what symbols should be added to  the  dynamic  symbol  table  if  the  output  format  supports  it.   See  the  description  of
       --dynamic-list.

       Note  that  this  option  is  specific  to  ELF  targeted  ports.   PE  targets  support  a  similar function to export all symbols from a DLL or EXE; see the description of
       --export-all-symbols below.

您也可以将-rdynamic选项传递给gcc / g ++(如注释中所述)。根据您设置make脚本的方式,这将很方便