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

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

DDD
DDDOriginal
2024-11-30 14:59:11437browse

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

Demystifying GCC's Weird Type Name Output using typeid.name()

When working with type information in C , typeid.name() is a handy tool to obtain the type's name. However, using GCC, developers have encountered perplexing characters in its output. This article delves into the reasons behind this behavior and explores how to obtain unmangled type names.

The Mystery of Decorated Names

By default, GCC returns a "decorated name" for types, which includes additional information and is not human-readable. This is exemplified in the code snippet provided:

#include <iostream>
#include <typeinfo>

struct Blah {};

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

When compiled with GCC, the code outputs "4Blah" instead of the expected "Blah". This is because GCC has appended type-related information to the name, such as parameters and size.

Demangling Decorated Names

To obtain the unmangled name, we need to apply a process called "demangling." GCC provides the __cxa_demangle() function for this purpose, as well as the command-line tool c filt.

The following code demonstrates how to demangle the decorated name:

#include <iostream>
#include <typeinfo>

int main() {
  const char* decorated_name = typeid(Blah).name();
  char* unmangled_name = abi::__cxa_demangle(decorated_name, nullptr, nullptr, nullptr); // Windows: _ZNKSt7__cxxabiv117__class_type_info9can_catchEPv
  if (unmangled_name) {
    cout << unmangled_name << endl;
    free(unmangled_name);
  } else {
    cout << "Demangling failed" << endl;
  }  
  return 0;
}

When compiled with GCC, this code will now output "Blah", as expected.

Conclusion

While typeid.name() is a valuable tool for obtaining type information in C , it is crucial to understand how GCC mangles type names. By leveraging the demangling techniques described above, developers can extract the human-readable names of types, simplifying debugging and analysis.

The above is the detailed content of Why Does GCC\'s `typeid.name()` Return Weird Type 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