2014-10-10 70 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

相關問題