2

I was trying to build a class, which has a public function, that can access the private array members according to index.

#include <iostream>
#include <array>

class foo{
public:
    int get_value_from_table(int row_number){
        return table[row_number];
    }

private:
    constexpr static std::array<int, 2> table = {1,2};
    //void initialize_table();
};

int main() {
    foo a;
    int b = a.get_value_from_table(1);
    std::cout << b << std::endl;
    return 0;
}

get an undefined symbol foo::table error when build the code. How can I fix the bug?

Undefined symbols for architecture x86_64:
  "foo::table", referenced from:
      foo::get_value_from_table(int) in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Xuhang
  • 445
  • 5
  • 20

1 Answers1

2

The posted code should work as-is with C++17 and later.

Before C++17 static constexpr members also required a definition outside the class declaration.

constexpr std::array<int, 2> foo::table; // still allowed but no longer required in C++17

Related insight and pointers can be found under constexpr static member before/after C++17.

dxiv
  • 16,984
  • 2
  • 27
  • 49