Home >Backend Development >C++ >Why Does Passing a Static Const Int by Reference Cause an \'Undefined Reference\' Error in C ?
Undefined Reference to Static Const Int: A Resolution
In a recent programming scenario, a compilation error emerged with the message "Undefined reference to 'Bar::kConst'". The error originated from the following code snippet:
class Bar { public: static const int kConst = 1; void func() { foo(kConst); // Error-prone line } };
The error arose because the static constant member "kConst" was not defined. Typically, the compiler is expected to make the necessary substitution at compile-time. However, in this case, the function "foo" takes a "const int &" parameter, causing the compiler to favor a reference over substitution.
To resolve the issue, the following modification can be employed:
foo(static_cast<int>(kConst));
This approach forces the compiler to create a temporary "int" and pass a reference to it, allowing for successful compilation.
The behavior observed is intentional, as specified in the C standard (9.4.2/4), which states that when a static data member of constant integral type has a constant initializer, it can appear in integral constant expressions. However, it must still be defined in namespace scope if used in the program.
In the given code, passing the static data member by constant reference constitutes "use" as per the C standard (3.2/2). This means that the compiler is obligated to enforce the presence of a definition for "kConst".
While GCC may sometimes overlook this requirement in certain scenarios, it is generally advisable to adhere to the standard and refrain from using references to or taking addresses of non-existent objects.
The above is the detailed content of Why Does Passing a Static Const Int by Reference Cause an \'Undefined Reference\' Error in C ?. For more information, please follow other related articles on the PHP Chinese website!