Home >Backend Development >C++ >Why Am I Getting an 'Undefined Reference to Typeinfo' Error in C ?

Why Am I Getting an 'Undefined Reference to Typeinfo' Error in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 16:57:18604browse

Why Am I Getting an

Undefined Reference to Typeinfo: Causes and Resolution

The dreaded "undefined reference to typeinfo" error can plague C developers, leaving them puzzled about its origins. Behind the scenes, this error arises when the linker stumbles upon a virtual function declaration without its corresponding definition.

Virtual functions are designed to be overridden in derived classes, enabling polymorphic behavior. However, declaring a virtual function without its definition implies that the definition is elsewhere. This forces the linker to search external compilation units or libraries for the missing definition. If the linker fails to locate it, the "undefined reference to typeinfo" error appears.

Consider this declaration:

This declaration informs the compiler that fn() is a virtual function but does not provide its implementation. The linker will flag this as an unresolved symbol during the linking stage, resulting in the error.

To rectify this, you must provide a definition for the virtual function:

By attaching a definition to the declaration, the linker no longer needs to search for a missing symbol.

This error is analogous to the following code snippet:

In this case, i is declared as an external variable located in another compilation unit. This requires the linker to resolve the external reference, but if it cannot locate i, it will report an unresolved symbol error.

By understanding the fundamental cause of the "undefined reference to typeinfo" error, developers can promptly troubleshoot and resolve the issue by providing proper definitions for virtual functions or handling external symbol references appropriately.

The above is the detailed content of Why Am I Getting an 'Undefined Reference to Typeinfo' Error in C ?. 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