1

I am using gcc (Debian 4.4.5-8) 4.4.5. with the following code, I am getting linking error :

/tmp/ccOeGgC9.o: In function A::func()':
(.text+0x1b): undefined reference to
B::CONST_B'
(.text+0x23): undefined reference to `A::CONST_A'

header:

class A {
    public:
    static const int CONST_A = 10;
    int func();
};
class B {
    public:
        static const int CONST_B = 20;
};

cpp file (with linking error):

int A::func() {
    bool c = true;
    const int a = (c == true) ? B::CONST_B : CONST_A;
}

int main() {
    return 0;
}

to fix the error, I have to write cpp file follow:

cpp file(working):

int A::func() {
    bool c = true;
    int a = CONST_A;
    a = (c == true) ? B::CONST_B : a;
}

int main() {
    return 0;
}

can you please explain why I can't compile first code?

Masoud
  • 29
  • 3
  • I don't see how your example is giving the linker error. `CONST_B` and `CONST_A` aren't odr-used in that case. http://coliru.stacked-crooked.com/a/0e25fcbbc9d39dab – David G Mar 18 '15 at 18:14
  • I tried it with newer version of gcc and I didn't see that linker error, but I can only compile my code with gcc (Debian 4.4.5-8) 4.4.5 – Masoud Mar 18 '15 at 18:44
  • @0x499602D2 these sort of ODR violations require no diagnostic, so a clean compile doesn't prove that the code is correct – M.M Mar 18 '15 at 23:48

1 Answers1

0
class A {
    public:
    static const int CONST_A = 10;
    int func();
};

static members like CONST_A in this example must have their definition outside the class

like this

class A {
   public:
   static const int CONST_A = 10;
   int func();
};

const int A::CONST_A = 10;
Sly_TheKing
  • 518
  • 7
  • 14
  • If that was the case, I should see the linker error in both case, but only the first code gives error – Masoud Mar 18 '15 at 18:30
  • @Masoud Not true. [Some violations of the ODR must be diagnosed by the compiler. Other violations, particularly those that span translation units, are not required to be diagnosed.](http://en.wikipedia.org/wiki/One_Definition_Rule#Summary) – David Schwartz Mar 18 '15 at 21:11