Undefined References with Static Constant References
When implementing a function with a reference to a static constant, such as const int & a, the compiler may encounter an "Undefined reference" error. This error stems from the fact that, although the constant is declared as static, it is not defined in the context where the function is called.
According to the C standard (9.4.2/4), a static data member of a const integral type can be initialized with a constant-initializer in its declaration. However, when used in a function parameter, passing it by constant reference constitutes "using" it (as per 3.2/2) and triggers the requirement for its definition within the namespace scope.
In the provided example, the static constant kConst is used in the function foo via the line foo(kConst). As the constant is not defined anywhere, the compiler attempts to create a reference to an undefined object. To resolve this, the developer must either provide a definition for kConst or pass the constant by value (forcing a temporary object creation), as demonstrated in the example's proposed solution.
While GCC may allow passing the constant by value (via static_cast
The above is the detailed content of Why do I get \'Undefined Reference\' errors when passing static constant references to functions?. For more information, please follow other related articles on the PHP Chinese website!