Reputation: 480
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.
Upvotes: 4
Views: 299
Reputation: 480
Compiler error was due to the C++11
standard.
Using C++17
standard by compiling above code using
g++ --std=c++17 test.cpp
produces no errors.
EDIT: This solution applies to C++17
and not C++11
as in my original question. For C++11
solution see accepted answer.
Upvotes: 1
Reputation: 66200
Before C++17 (so C++11 and C++14) you have to add
constexpr int Foo::arr[3][2];
outside the body of class.
Upvotes: 6