Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typeid.name() return weird characters using GCC and how to make it print unmangled names?

Tags:

c++

gcc

g++

rtti

How come when I run this main.cpp:

#include <iostream> #include <typeinfo>  using namespace std;  struct Blah {};  int main() {   cout << typeid(Blah).name() << endl;   return 0; } 

By compiling it with GCC version 4.4.4:

g++ main.cpp 

I get this:

4Blah 

On Visual C++ 2008, I would get:

struct Blah 

Is there a way to make it just print Blah or struct Blah?

like image 700
sivabudh Avatar asked Dec 16 '10 22:12

sivabudh


People also ask

What does Typeid name return C++?

The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr. You must include the standard template library header <typeinfo> to use the typeid operator.

What is type id pc?

typeid is an operator in C++. It is used where the dynamic type or runtime type information of an object is needed.

How do you use Typeid?

To use the typeid operator in a program, one needs to include the library header <typeinfo>. It returns the lvalue of type const type_info to represent the type of value. Expression of typeid is an lvalue expression (lvalue has the address which is accessible by the program.

What is Typeinfo C++?

The class type_info holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the typeid operator. The type_info class is neither CopyConstructible nor CopyAssignable.


2 Answers

The return of name is implementation defined : an implementation is not even required to return different strings for different types.

What you get from g++ is a decorated name, that you can "demangle" using the c++filt command or __cxa_demangle.

like image 81
icecrime Avatar answered Sep 22 '22 13:09

icecrime


The string returned is implementation defined.

What gcc is doing is returning the mangled name.
You can convert the mangled name into plain text with c++filt

> a.out | c++filt 
like image 25
Martin York Avatar answered Sep 22 '22 13:09

Martin York