- 1 year ago
How to find the type_info symbol without using /export (for unit tests)
To find the type_info
symbol without using /export
for unit tests in C++, you can use a technique called "Weak Symbol Interposition" or "Symbol Redefinition." This technique allows you to override the type_info
symbol in your unit test code, effectively replacing the original implementation with a mock or test-specific version.
Here's a step-by-step guide on how to achieve this:
Create a Test-Specific Implementation:
In your unit test code, create a test-specific implementation of thetype_info
symbol. You can define a dummytype_info
structure or any other implementation that suits your testing needs.For example, you can create a mock
type_info
structure like this:cpp// TestTypeInfo.h (header file for the test-specific type_info)
struct TestTypeInfo {
// Add members or functions specific to your tests
};
Link the Test Implementation:
Link your unit test code with the test-specifictype_info
implementation. This will ensure that the test-specific implementation is used instead of the standard implementation provided by the C++ runtime.Define a Weak Symbol:
In your test code, define a weak symbol fortype_info
to use your test-specific implementation. This tells the linker to use the weak symbol if it's available (i.e., if it's defined in your test code), otherwise, it falls back to the default implementation from the C++ runtime.cpp// TestTypeInfo.cpp (source file for the test-specific type_info)
#include "TestTypeInfo.h"
// Define a weak symbol for type_info
__attribute__((weak)) const TestTypeInfo type_info;
Use the Test-Specific
type_info
:
In your unit test code, you can now use thetype_info
symbol, and it will resolve to the test-specific implementation defined inTestTypeInfo.cpp
.cpp// UnitTest.cpp (your actual unit test code)
#include "TestTypeInfo.h"
void runUnitTest() {
// Use the test-specific type_info
const TestTypeInfo& ti = type_info;
// Perform your unit test logic
}
By following these steps, you can replace the type_info
symbol with a test-specific implementation for your unit tests, allowing you to test code that uses type_info
without relying on the /export
option or making changes to the original implementation. Keep in mind that this technique works for most modern compilers like GCC and Clang, which support weak symbols, but the syntax may vary slightly between different compilers.