Wednesday 22 November 2017

c++ - Undefined reference to static constexpr char[]

itemprop="text">

I want to have a static
const
char array in my class. GCC complained and
told me I should use constexpr, although now it's telling me
it's an undefined reference. If I make the array a non-member then it compiles. What is
going on?



//
.hpp

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

// .cpp
void
foo::bar() {
std::string str(baz); // undefined reference to
baz
}



Answer




Add to your cpp
file:



constexpr char
foo::baz[];


Reason:
You have to provide the definition of the static member as well as
the declaration. The declaration and the initializer go inside the class definition, but
the member definition has to be separate.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...