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

3

11

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.

Adrienadriena answered 9/2, 2011 at 17:35 Comment(1)
Point of reference: Using g++ -c blah.o blah.cpp does not include class names until after linking it as an executable.Parts
G
13

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.

Galactose answered 9/2, 2011 at 17:40 Comment(5)
Yeah, it looks to be RTTI, I compiled again with -fno-rtti and the class names don't appear in the strings output.Adrienadriena
@Xeno: gcc returns the mangled name of a class when you you use typeid(x).name().Shelleyshellfire
I just compiled my code with -fno-rtti and I still see names of functions in the strings output...Agni
I am not sure about that, but function names might not be the same as class names.Galactose
In my case I need to use strip since using -fno-rtti seems to have no effect when compiling my program since the compiled binary still contain my template class name I predict this happens because I explicitly instantiate my template classMistranslate
K
4

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.

Knowle answered 9/2, 2011 at 17:43 Comment(1)
note that disabling RTTI usually disable exceptions as well, since RTTI and exception handling usually share a number of mechanics.Shelleyshellfire
B
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.

Busywork answered 9/2, 2011 at 17:41 Comment(2)
this does not actually require storing the name, only an id. A hash, for example, would work too.Shelleyshellfire
Good thing I never claimed that it did.Busywork

© 2022 - 2024 — McMap. All rights reserved.