Home > Backend Development > C++ > Why Does My C Code Produce 'undefined reference to typeinfo' Errors?

Why Does My C Code Produce 'undefined reference to typeinfo' Errors?

DDD
Release: 2024-12-04 12:34:10
Original
643 people have browsed it

Why Does My C   Code Produce

Understanding "g undefined reference to typeinfo" Errors

When encountering "undefined reference to typeinfo" linker errors, it's crucial to delve into the underlying reasons behind these messages. One potential cause lies in declaring virtual functions without providing their definitions.

Virtual functions allow for polymorphism, enabling derived classes to override and provide different implementations for methods inherited from their base classes. However, when a virtual function is declared without a definition, the compiler indicates that the implementation is provided elsewhere. This means the linker will attempt to find the missing definition during the linking stage, referencing other compilation units or libraries.

To eliminate this error, the virtual function must be accompanied by a definition. This associates the function declaration with its implementation, preventing the linker from attempting to resolve the reference later. A defined virtual function appears as:

virtual void fn() { /* insert code here */ }
Copy after login

In contrast, a virtual function declaration without a definition resembles:

virtual void fn();
Copy after login

This declaration fails to provide the definition, resulting in the "undefined reference to typeinfo" error.

Analogously, it's comparable to declaring an external variable without defining it:

extern int i;
int *pi = &i;
Copy after login

In this instance, the compiler indicates that the 'i' integer is declared elsewhere and must be resolved during linking. Otherwise, pi cannot refer to its address.

The above is the detailed content of Why Does My C Code Produce 'undefined reference to typeinfo' Errors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template