Why does g++ store class names in the compiled binary?

痴心易碎 提交于 2020-01-14 07:12:14

问题


I noticed that If I run strings on my program which was compiled by g++ the output contains the names of various classes that it uses.

The program was compiled with -O3 and without -g or -p, and the class names are still present when I strip the binary.

I was wondering why it is necessary for g++ to store this information in the binary? The class names that are present all seem to be classes that use virtual functions, so I suspect this is something to do with it.


回答1:


This might have something to do with RTTI, specifically, RTTI allows you to query the name of the class of a given variable. See the typeid keyword. If this is the case then it would explain why it happens only with classes which have virtual functions - RTTI works only for classes with virtual functions.

Edit: As @xeno pointed out, it is indeed RTTI, and if you add -fno-rtti the class names don't appear in the strings output.




回答2:


g++ has RTTI enabled by default. Use the -fno-rtti switch if you don't need RTTI and you'll find the strings are not present.




回答3:


Yes, it probably has to do with how g++ implements RTTI. It needs to be able to search through a class tree for the right type during runtime, so it has to store that tree somehow. Any class with a virtual function is considered "polymorphic" and requires special RTTI information be included in the executable. The standard doesn't say how this is done though, but class names makes about as much sense as anything.



来源:https://stackoverflow.com/questions/4948381/why-does-g-store-class-names-in-the-compiled-binary

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