Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code broken or is there a bug in g++?

Tags:

For some strange reason g++ (versions 4.5.0 and 4.5.2) cannot compile this code:

bool somefunc() {
    return false;
}

class C {
  public:
    static const int a = 0;
    static const int b = 1;
};

class myclass {
  public:
    int check() {
        return somefunc() ? C::a : C::b;
        // if(somefunc()) return C::a; else return C::b;
    }
};

int main() {
    myclass obj;
    obj.check();
    return 0;
}

It gives me this error:

/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::a'
/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::b'
collect2: ld returned 1 exit status

What's strange if I change problematic line to the commented line it compiles fine. Is it something wrong with my code and something I don't understand about C++ or is it just a bug in G++ ?

like image 510
matix2267 Avatar asked Jul 11 '11 18:07

matix2267


1 Answers

There is an ongoing debate on whether this code is actually legal or not.

Either way, according to some readings the constants actually do need to be defined before usage, not just declared. That is,

class C {
  public:
    static const int a = 0;
    static const int b = 1;
};

const int C::a;
const int C::b;

Or just use the enum hack that was used to accomodate older compilers (but which may after all be the only legal way):

class C {
  public:
    enum { a = 0, b = 1 };
};
like image 100
Konrad Rudolph Avatar answered Oct 17 '22 03:10

Konrad Rudolph