Home > Article > Backend Development > Why Do I Get the \"Undefined Reference to \'Bar::kConst\'\" Error in C ?
Undefined Reference to 'Bar::kConst' Error in C
In C , when a program attempts to reference a static const member variable within a class, such as Bar::kConst in the given code snippet, it may encounter an "Undefined reference to 'Bar::kConst'" error. This error indicates that the compiler cannot find the definition for the variable.
According to C standards (section 9.4.2/4), a static data member with a constant integral or enumeration type can be initialized in the class definition. However, it must still be explicitly defined in a namespace scope if it is used in the program.
In the example provided, the static const int kConst is declared within the Bar class, but not defined, as it is initialized in the declaration. When the foo function is called within the Bar::func method, it attempts to pass kConst by const reference. This is considered a "use" of the variable, as per C standard (section 3.2/2). Since the variable is not explicitly defined, the compiler cannot perform the necessary substitution and raises the error.
To resolve this error, one can either explicitly define the kConst variable in a namespace scope or, as shown in the code snippet, explicitly convert kConst to a temporary int using a static_cast, forcing the compiler to perform the substitution at compile time.
In conclusion, the "Undefined reference to 'Bar::kConst'" error occurs because the static const member variable is not explicitly defined, which is required when it is used in the program. It is important to adhere to the C standards when declaring and using static data members to prevent such errors.
The above is the detailed content of Why Do I Get the \"Undefined Reference to \'Bar::kConst\'\" Error in C ?. For more information, please follow other related articles on the PHP Chinese website!