Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 760
Xeno Avatar asked Feb 09 '11 17:02

Xeno


3 Answers

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.

like image 147
sashoalm Avatar answered Nov 01 '22 03:11

sashoalm


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.

like image 34
Steve Avatar answered Nov 01 '22 03:11

Steve


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.

like image 21
Edward Strange Avatar answered Nov 01 '22 01:11

Edward Strange