Home > Backend Development > C++ > Why Does My Static `constexpr char` Array Cause an 'Undefined Reference'?

Why Does My Static `constexpr char` Array Cause an 'Undefined Reference'?

Patricia Arquette
Release: 2024-12-21 15:15:23
Original
484 people have browsed it

Why Does My Static `constexpr char` Array Cause an

Undefined Reference to Static constexpr char[]

When attempting to create a static const char array as a member of a class, you may encounter the error "undefined reference to baz."

Explanation:

GCC requires you to use constexpr for static const arrays. However, placing the array declaration and initializer within the class definition alone is not sufficient. You must also provide a separate member definition in the .cpp file.

To resolve this:

  1. In your .cpp file, add the following line after the class declaration:

    constexpr char foo::baz[];
    Copy after login

    This declares the definition of the static member baz.

  2. Leave the declaration and initialization of the array within the class definition:

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

Reason:

The class definition provides the declaration and initializer of the static member. However, the member definition, which allocates memory and initializes the array, needs to be provided separately in the .cpp file. By adding this definition, the linker will be able to find the symbol baz and resolve the undefined reference.

The above is the detailed content of Why Does My Static `constexpr char` Array Cause an 'Undefined Reference'?. 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