Run-time type information (RTTI) enables C++ programs to determine an object's dynamic type using features such as typeid and dynamic_cast. While RTTI is enabled by default on most toolchains, some projects - especially those targeting embedded systems or seeking minimum binary size - disable it intentionally. When working in such mixed environments, it can be useful for the code to detect whether RTTI support is turned on and adapt its behavior accordingly. This tutorial shows how to check if RTTI is enabled using C++.
Different compilers expose different indicators for RTTI availability:
- Clang provides the
__has_feature(cxx_rtti)check, which can be used to detect whether RTTI is available. If it is, you can define your own macro to indicate RTTI support. Clang does not automatically define__GXX_RTTI. - GCC, in contrast, does not support
__has_feature, but it automatically defines__GXX_RTTIwhenever RTTI is enabled. - MSVC defines
_CPPRTTIif RTTI is enabled.
Using these macros, we can implement a portable check:
#include <iostream>
#ifdef __has_feature
#if __has_feature(cxx_rtti)
#define __GXX_RTTI
#endif
#endif
#if defined(__GXX_RTTI) || defined(_CPPRTTI)
#define RTTI_ENABLED 1
#else
#define RTTI_ENABLED 0
#endif
int main() {
if (RTTI_ENABLED) {
std::cout << "RTTI enabled" << std::endl;
} else {
std::cout << "RTTI not enabled" << std::endl;
}
return 0;
}
To test the macro logic, compile the program with RTTI disabled by passing the appropriate option to the compiler:
g++ -fno-rtti main.cpp -o test
Then run the executable:
./test
The program will print whether RTTI support is available. This technique is particularly useful when maintaining code intended to run in both RTTI-enabled and RTTI-disabled configurations.
Leave a Comment
Cancel reply