I want to create a constant and static integer array as a public class variable. It is neat to define it and initialize it right away. See code below for complete example.
#include <iostream>
class Foo {
public:
constexpr static int arr[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
};
int main() {
for (int i = 0; i < 3; i++) {
std::cout << "Pair " << Foo::arr[i][0] << ", " << Foo::arr[i][1] << std::endl;
}
return 0;
}
However, compiling code above using g++ --std=c++11 test.cpp
produces
/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status
Is this not possible in C++ ? More likely I am missing some part about C++ and its static variable initialization policy.
Before C++17 (so C++11 and C++14) you have to add
constexpr int Foo::arr[3][2];
outside the body of class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With