1

I am reading "C++17 The Complete Guide" by Nicolai Josuttis, and I didn't understand the following: why in C++14 following code is not working

struct D
{
    static constexpr int n = 5;   
};

int inc(const int& n)
{
   return n; 
}

int main()
{
    std::cout << inc(D::n) << std::endl;
}

returning following error

main.cpp:(.text+0x15): undefined reference to `D::n'

while this other

struct D
{
    static constexpr int n = 5;   
};

int main()
{
    std::cout << D::n << std::endl;
}

is perfectly fine?

fabiop
  • 179
  • 10
  • 1
    The rules regarding static member variables changed between C++14 and C++17. For C++14 (and before) you need to do an out-of-class definition. In the first example it's needed because you [**ODR-use**](https://en.cppreference.com/w/cpp/language/definition#ODR-use) the variable. You don't do that in the second example, and the compiler might let that slip. – Some programmer dude Aug 15 '23 at 08:13

0 Answers0