Home >Backend Development >C++ >Why Does g Produce 'Undefined Reference to typeinfo' Errors?

Why Does g Produce 'Undefined Reference to typeinfo' Errors?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 06:18:10246browse

Why Does g   Produce

G : Understanding "Undefined Reference to Typeinfo" Errors

The "undefined reference to typeinfo" error is often encountered when compiling C programs with g . It signifies that the linker cannot find the type information for a particular class, which could have several causes.

Cause: Declaring Virtual Functions Without Definitions

One common reason for this error is declaring virtual functions without providing their definitions in the same compilation unit. When you declare a virtual function without defining it, you suggest that its definition exists elsewhere, either in subsequent compilation units or external libraries.

Therefore, during the linking phase, the compiler searches for the virtual function's definition in other object files or libraries. If it cannot locate the definition, it raises the "undefined reference to typeinfo" error.

Example: Incorrect Declaration

virtual void fn();

This declaration informs the compiler that a virtual function named fn() exists, but it does not provide a concrete implementation.

Example: Correct Definition

virtual void fn() { /* Implementation code here */ }

When you provide a definition to the virtual function, the linker no longer needs to search for it elsewhere, resolving the error.

Analogy: External Variable Resolution

The behavior is akin to declaring an external variable in one compilation unit and attempting to access it in another unit without providing an explicit definition:

extern int i;
int *pi = &i;

Here, the variable i is declared externally, indicating that its definition lies in another compilation unit. If this definition is not available at link time, the compiler will generate an "undefined reference" error.

Understanding the root cause of this error is crucial to avoiding it and ensuring successful compilation of your C code.

The above is the detailed content of Why Does g Produce 'Undefined Reference to typeinfo' Errors?. 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