Home >Backend Development >C++ >Why Does GCC\'s `typeid.name()` Return Unreadable Names, and How Can I Fix It?

Why Does GCC\'s `typeid.name()` Return Unreadable Names, and How Can I Fix It?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 05:22:14166browse

Why Does GCC's `typeid.name()` Return Unreadable Names, and How Can I Fix It?

GCC's typeid.name() Peculiarities

The typeid.name() function is often utilized to obtain information about the type of a variable or expression. However, when compiling with GCC, it has been observed that this function returns seemingly nonsensical characters instead of the expected unmangled type name. This behavior stands in contrast to other compilers like Visual C , which provide a clearer representation.

The Reason Behind the Discrepancy

The discrepancy lies in the implementation of typeid.name(), which is defined by the compiler's implementation. GCC, for instance, returns a decorated name, which includes additional information about the type, such as the name and signature of constructors and destructors.

Demangling the Decorated Name

To obtain a more readable type name from the decorated string, you can use tools such as c filt or __cxa_demangle. These tools "demangle" the decorated name, removing the extra information and leaving you with the unmangled type name.

Example: Demangling with c filt

#include <iostream>
#include <typeinfo>

using namespace std;

struct Blah {};

int main() {
  cout << c++filt::demangle(typeid(Blah).name()) << endl;
  return 0;
}

When you compile and execute this modified code, you will get the desired output:

struct Blah

Conclusion

Although GCC's typeid.name() function initially returns a decorated type name, it is possible to demangle it to obtain the unmangled type name using tools like c filt or __cxa_demangle. By understanding the implementation-defined nature of typeid.name(), you can effectively retrieve the desired type information in your C code.

The above is the detailed content of Why Does GCC\'s `typeid.name()` Return Unreadable Names, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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