Strange C++ link error

Viewed 217

When I try to compile this,

#include <iostream>

struct K{
    const static int a = 5;
};

int main(){
    K k;

    std::cout << std::min(k.a, 7);
}

I get following. Both gcc and clang gives similar error:

/tmp/x-54e820.o: In function `main':
x.cc:(.text+0xa): undefined reference to `K::a'
clang-3.7: error: linker command failed with exit code 1 (use -v to see invocation)

if I do following, it compiles without problem. Is this related to the way std::min is written?

#include <iostream>

struct K{
    const static int a = 5;
};

int main(){
    K k;

    std::cout << std::min((int) k.a, 7);  // <= here is the change!!!
}

another way to avoid the error is if I do my own min():

template <class T>
T min(T const a, T const b){
    return a < b ? a : b;
}

C-like preprocessor MIN also works OK.

3 Answers
Related