Search code examples
c++inlinec++17constexprstatic-members

Why can't a static constexpr member variable be passed to a function?


The following code produces an undefined reference to 'Test::color'.

#include <iostream>

struct Color{
    int r,g,b;
};

void printColor(Color color) {
    //printing color
}

class Test {
    static constexpr Color color = {242,34,4};
public:
    void print(){
        printColor(color);
    }
};


int main() {
    Test test;
    test.print();

    return 0;
}

Why does this code produce the above error and what is the best way to avoid it, considering I want to use the latest version of the standard, C++17?

Should I define the static member variable, just like it was needed in earlier revisions of the standard (see the first answer here: Undefined reference to static constexpr char[]) or should I just create a new Color structure as can be seen below?

printColor(Color{color.r, color.g, color.b});

Edit: I'm using CLion on Ubuntu 16.04, which as far as I could find out, uses g++ 5.4 for compiling. I have set it to use C++17 and still get the same error. The error is only present when color is passed to a function.


Solution

  • The problem was neither with the code itself, nor with the standard being used. CLion's default compiler does not fully support C++17, so that's why it showed a strange behavior that it could compile static constexpr member variables, but only as long as they were not passed to functions.

    After updating to the most recent compiler version, I was able to run the code successfully without any changes.

    Thank you for all your contribution.