2

I suppose that there is something terribly wrong with this code. It will compile but does not get linked.

#include <iostream>
#include <tuple>

class Table_class
{
    public:
    constexpr static std::tuple<int, unsigned int, unsigned short> table[3]
    = {std::make_tuple(1, 2, 3),
        std::make_tuple(4, 5, 6),
        std::make_tuple(7, 8, 9)};
};

int main()
{
    std::cout << std::get<0>(Table_class::table[0]);
    return 0;
}

The error that shows up is this:

[31m/tmp/ccDiIuPv.o: In function `main':
file.cpp:(.text+0x5): undefined reference to `Table_class::table'
collect2: error: ld returned 1 exit status

Compilation Failed

How can this be corrected?

bowzee
  • 23
  • 3
  • 2
    Possible duplicate of [C++ initialize static variables in class?](http://stackoverflow.com/questions/5019856/c-initialize-static-variables-in-class) – Ari0nhh Aug 11 '16 at 04:25

2 Answers2

4

It's not terribly wrong. Your code is (will be) perfectly legal in C++17. However, before C++17, static constexpr data members need to be defined outside of class, so find somewhere and add the following definition:

constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table[3];

demo.

As usual, variable definition should not be in a header file.

cpplearner
  • 13,776
  • 2
  • 47
  • 72
  • The solution works and solves the problem, but, when used as part of a .h or .cpp file, it has this drawback of having to define that line in the routine that calls it. Fingers crossed for C++17 !!! – bowzee Aug 11 '16 at 16:14
1

It's a common source of linking errors. You have to define the table outside the class definition, to make the linker find it. A simplified example:

#include <iostream>
#include <tuple>

class Table_class
{
    public:
    constexpr static std::tuple<int, unsigned int, unsigned short> table = std::make_tuple(1, 2, 3);

};

constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table;
int main()
{
    std::cout << std::get<0>(Table_class::table);
    return 0;
}
dau_sama
  • 4,247
  • 2
  • 23
  • 30