Home  >  Article  >  Backend Development  >  Why do I get \"Undefined Reference\" errors when passing static constant references to functions?

Why do I get \"Undefined Reference\" errors when passing static constant references to functions?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 18:46:03582browse

Why do I get

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(kConst)), it adheres strictly to the standard when passing it by reference. This error serves as a reminder to define static constants or use them by value when passing to functions that take constant references.

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!

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