Home > Backend Development > C++ > Why Do I Get an 'Undefined Reference' Error with Static constexpr Char Arrays in C ?

Why Do I Get an 'Undefined Reference' Error with Static constexpr Char Arrays in C ?

Linda Hamilton
Release: 2024-12-23 04:07:27
Original
444 people have browsed it

Why Do I Get an

Undefined Reference to Static constexpr Char Array: Understanding the Undefined Reference Issue

In the C programming language, it is possible to define static constant character arrays within a class. However, developers may encounter an "undefined reference" error when attempting to reference such arrays in their code. This error occurs because the compiler requires both a declaration and a definition of the static member.

To resolve this issue, the code should be modified as follows. In the class definition (.hpp file), the declaration and initialization of the static array should remain inside the class. In the implementation file (.cpp file), a separate line should be added to provide the definition of the static array.

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

// .cpp
void foo::bar() {
  std::string str(baz); // now compiles successfully
}

constexpr char foo::baz[]; // definition of static member
Copy after login

By providing the definition of the static member separately, the compiler can link the reference to the array correctly, resolving the undefined reference error. This separation between declaration and definition is necessary because the array's size must be known during compilation, while its initialization can be deferred until later.

The above is the detailed content of Why Do I Get an 'Undefined Reference' Error with Static constexpr Char Arrays in C ?. 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