【问题标题】:having object file symbols become dynamic symbols in executable让目标文件符号成为可执行文件中的动态符号
【发布时间】:2014-12-05 08:28:17
【问题描述】:

我有几个从构建系统中吐出的目标文件(来自 C++)。他们有几个我想在程序中使用的extern "C"-linkage 符号,并且可以从其他地方通过dlopen/dlsym 访问。

当使用 gcc 编译成可执行文件时,这些符号不会使用 nm -D <executable-here> 列出(即 afaik 它们不是动态符号)。

如何让它们在编译后的可执行文件中显示为动态符号?

我可以更改目标文件和可执行文件的构建标志,但更改 C++ 文件在最终可执行文件中的结束方式(即不首先将它们变成目标文件)是困难的。

(GCC 4.8,ld 2.24)

编辑:我遇到了这个问题,这可能是也可能不是我要问的问题,但我并不完全确定。 Use dlsym on a static binary

【问题讨论】:

  • 那么您也想将您的可执行文件用作共享库吗?通常,构建一个供多个应用程序使用的共享库是这里常用的方法。
  • 对编辑的回应:是的,它和我的评论说的差不多:要么使用公共共享库,要么不使用dlopendlsym...
  • 是的...所以,奇怪的是:我在程序中嵌入了一个 Java VM,它使用 JNA/dlopen/dlsym 来访问外部 C 函数。最好将所有内容保存在一个可执行文件中,这样我就不需要在开发过程中弄乱链接器路径。如果我几乎必须制作一个共享库,那么,嗯,好吧……

标签: c++ g++ ld dlopen dlsym


【解决方案1】:

你不妨看看--export-dynamicld 选项:

   -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.

另外,如果链接期间没有任何对象引用您的外部符号,您可能希望将它们放入--dynamic-list 以确保它们被导出。


例子:

$ cat test.cc
#include <stdio.h>

int main() {
    printf("Hello, world\n");
}

extern "C" void export_this() {
    printf("Hello, world from export_this\n");
}

$ g++ -o test -W{all,extra} -Wl,--export-dynamic test.cc

$ ./test
Hello, world

$ nm --dynamic test | grep export_this
00000000004007f5 T export_this # <---- here you go

【讨论】:

  • 我实际上尝试了这个(很抱歉在问题中没有提到这一点)以及与 afaik 密切相关的 -rdynamic 标志,但不知何故它没有成功。不过,我可能只是做错了。 -.-'
  • 您可以尝试将您的符号放入--dynamic-list 以确保它们被导出。
  • 刚刚做了(通过-Wl,--dynamic-list &lt;my-symbol-here&gt;使用gcc);奇怪的是,仍然出现符号未找到错误。我想我会举手并滥用共享对象的 rpath...
  • 这不是赢家的态度;)
  • :-/ 你说的是明智的真理。我想我会在某个时候重新审视它;我觉得这里写的应该有效。
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2021-09-19
  • 2018-07-12
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
相关资源
最近更新 更多