Home > Backend Development > C++ > Why Does GCC\'s `typeid.name()` Return Mangled Names Instead of Plain Type Names?

Why Does GCC\'s `typeid.name()` Return Mangled Names Instead of Plain Type Names?

Mary-Kate Olsen
Release: 2024-11-22 11:50:12
Original
850 people have browsed it

Why Does GCC's `typeid.name()` Return Mangled Names Instead of Plain Type Names?

GCC's Mangled Type Names: Demystifying the 'typeid.name()' Conundrum

When utilizing the 'typeid.name()' function with GCC, users may be surprised by the peculiar strings it returns. Unlike other compilers that provide unmangled class or struct names, GCC outputs a decorated name full of potential bafflement.

Delving into the Problem

Consider the following C code:

#include <iostream>
#include <typeinfo>

using namespace std;

struct Blah {};

int main() {
  cout << typeid(Blah).name() << endl;
  return 0;
}
Copy after login

Compiling this code with GCC 4.4.4 yields the perplexing result:

4Blah
Copy after login

In contrast, Visual C 2008 would have returned:

struct Blah
Copy after login

Unveiling the Mystery

The reason for this discrepancy lies in the implementation-defined nature of 'typeid.name()'. An implementation may elect to return dissimilar strings for distinct types or even identical strings for different types.

GCC's Decorated Names

GCC, by design, returns a decorated name for type information. This decorated name is a complex string that encompasses various details about the type, including its name and associated template arguments.

Demangling the Decorated Name

To make sense of GCC's decorated names, one can employ the 'c filt' command or the '__cxa_demangle' function. These tools enable the demangling of decorated names, revealing the underlying unmangled class or struct name.

Conclusion

While the behavior of 'typeid.name()' may vary across compilers, it is crucial to recognize the implementation-defined nature of its return. In the case of GCC, it returns decorated names, which require specialized tools to demangle for readability.

The above is the detailed content of Why Does GCC\'s `typeid.name()` Return Mangled Names Instead of Plain Type Names?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template