Robert Poenaru
Robert Poenaru

Reputation: 301

C++ access static constexpr array

I am trying to get some values from an array which is declared in another class. The array has a fixed length and constant elements (I will 100% never modify its values, so that's why I made it constant).

However, when I try to access the first element in the main function, I get a compilation error:

basavyr@Roberts-MacBook-Pro src % g++ -std=c++11 main.cc
Undefined symbols for architecture x86_64:
  "Vectors::vec1", referenced from:
      _main in main-c29f22.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1

As you can see, I'm compiling on macOS Catalina using clang (latest version).

[Q]:What could be the issue? Thank you in advance.

Here is the code:

#include <iostream>

class Dimension
{
public:
    static constexpr int dim1 = 2;
    static constexpr int dim2 = 1;
};

class Vectors
{
public:
    static constexpr double vec1[2] = {4.20, 6.9};
};

int main()
{
    auto a = Vectors::vec1[0]; //I also tried initializing this to a value rather than just accessing it directly through the class like I did below
    std::cout << a << "\n";
    std::cout << Vectors::vec1[0] << "\n"; 
    return 0;
}

Upvotes: 3

Views: 2237

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

You're compiling in C++11 mode; you need to provide definition for these constexpr static members at namespace scope. Note that this is not required since c++17.

If a const non-inline (since C++17) static data member or a constexpr static data member (since C++11) is odr-used, a definition at namespace scope is still required, but it cannot have an initializer. This definition is deprecated for constexpr data members (since C++17).

e.g.

class Dimension
{
public:
    static constexpr int dim1 = 2;
    static constexpr int dim2 = 1;
};

constexpr int Dimension::dim1;
constexpr int Dimension::dim2;

class Vectors
{
public:
    static constexpr double vec1[2] = {4.20, 6.9};
};

constexpr double Vectors::vec1[2];

Upvotes: 9

Related Questions