2014-10-10 150 views
1

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

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

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

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

(GCC 4.8,LD 2.24)

编辑:我碰到这个问题,可能会或可能不会是我在问什么,但我不能完全肯定。 Use dlsym on a static binary

+0

所以,你想用你的可执行文件太共享库?通常情况下,构建一个由多个应用程序使用的共享库是通常的方法。 – 2014-10-10 08:23:05

+0

编辑的回应:是的,它几乎说我的评论说同样的事情:要么使用共同的共享库,要么不使用'dlopen'和'dlsym' ... – 2014-10-10 08:25:08

+0

是的......所以,奇怪:我在程序中嵌入了一个Java VM,它使用JNA/dlopen/dlsym来访问extern C函数。最好将所有内容保存在一个可执行文件中,这样我就不需要在开发过程中混淆链接器路径。如果我非常*有*做共享库,那么,meh,'凯... – user 2014-10-10 08:28:49

回答

1

你可能想看看--export-dynamic 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. 

另外,如果没有链接中的对象是指你的外部符号,你可能想将其付诸--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 
+0

我实际上给了这个尝试(遗憾的是不提及在问题中)与afaik密切相关的'-rdynamic'标志,不知怎的,它没有成功。不过,我可能刚刚做错了。 -'-' – user 2014-10-10 08:36:52

+0

您可以尝试将您的符号放入'--dynamic-list'中以确保它们已被导出。 – 2014-10-10 08:38:19

+0

刚刚做过(使用gcc通过'-Wl, - dynamic-list ');奇怪的是仍然得到符号未发现的错误。我想我要扔掉我的手,并滥用与共享对象rpaths ... – user 2014-10-10 08:47:28

相关问题