0

How to properly access the string "bye" from the struct?

#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };

int main(int argc, char *argv[]) {
  typedef struct S ST;

  std::cout << hi << std::endl;              // this prints "hi" 
  std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
  std::cout << ST::bye << std::endl;         // this does not compile with "undefined reference"
}

I'm working with a c++ framework that has some configuration in this format (in multiply nested structs even) to make its values available during compile time. I'm not deep enough into C++ to grasp the underlying issue here. Also I cannot argue about why this approach on implementing the configuration was chosen and cannot change it.

Unchained
  • 677
  • 7
  • 8

1 Answers1

0

This can be made working by redefining the static constexpr outside the struct:

#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };

constexpr char S::bye[]; // <<< this line was missing

int main(int argc, char *argv[]) {
  typedef struct S ST;

  std::cout << hi << std::endl;              // this prints "hi" 
  std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
  std::cout << ST::bye << std::endl;         // Now this prints "bye"
}

Or by compiling using c++17 which makes this obsolete.

Related links:

Unchained
  • 677
  • 7
  • 8