Home > Backend Development > C++ > Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a Class Method?

Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a Class Method?

Barbara Streisand
Release: 2024-12-23 08:41:17
Original
783 people have browsed it

Why Do I Get an

Undefined Reference to Static constexpr char[]

When attempting to access a static constexpr character array within a class method, you may encounter an "undefined reference" error. This issue arises when the declaration and initialization of the array occur within the class definition, but the definition itself is omitted.

Problem:

// header file (.hpp)
struct foo {
  void bar();
  static constexpr char baz[] = "quz"; // Declaration and initialization
};

// implementation file (.cpp)
void foo::bar() {
  std::string str(baz); // "undefined reference to baz" error
}
Copy after login

Solution:

To resolve this issue, you must provide a separate definition for the static member in the implementation file (.cpp) in addition to the declaration in the class definition (.hpp):

// implementation file (.cpp)
constexpr char foo::baz[]; // Definition
Copy after login

Explanation:

The compiler needs both the declaration and the definition of the static member to know its memory location and its initial value. The declaration in the class definition only specifies the type and name of the member, whereas the definition provides the actual memory allocation and initialization. By separating the definition from the declaration, you ensure that the compiler has all the necessary information to link the member to its definition during compilation.

The above is the detailed content of Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a Class Method?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template