问题
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