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!