0

I'm relatively inexperience when it comes to debugging linker error. I don't see how this code setup that I have would cause the linker to throw an error. Please help point out my obliviousness.

// This is the header file
class A
{
public:
  //Constructor, methods, etc.

  static unsigned int const length = 5;
};

class B
{
public:
  // Constructor, methods, etc.

  inline unsigned int const & GetLength(void)
  {
    return A::length;
  }
};

I'm getting the linker error saying that in the source file (cpp) there's an undefined reference in the GetLength() function to 'A::length'. Does this means that I HAVE to define that function in the source file instead of the header? Why? I thought since I have the declaration of the variable in a class above, it should be able to find reference to that variable?

EDIT: Sorry if I sound ignorant, but I thought that with static variables of integral types, you can both define and declare it inside the class' definition, which is what I did. It's only with the non-integral type that you have to define it outside of the class' definition like in the duplicate post.

Thomas Phan
  • 249
  • 2
  • 17
  • @Bo Persson Could you please unmark this as duplicate? I've looked at the duplicated link and this is not the same problem. The other post was using a non-integral static variable inside the class' definition, thus he could not define it there. But mine is an integral type and I have already defined it inside the class. – Thomas Phan Apr 08 '17 at 16:51
  • If it had been `static const` it would have been enough with a declaration in the header. But now it needs a definition as well. – Bo Persson Apr 08 '17 at 17:01
  • Oh, as you return a reference to the value you would get in trouble also for the `const` version. A reference needs something to refer to. – Bo Persson Apr 08 '17 at 17:03
  • @BoPersson I apologize for not providing enough and inaccurate information. The static variable is a const. But I found out the problem I think after just blindly testing variations. I can't return a reference to a static variable? I took out the reference from the return type of the function and it built fine. – Thomas Phan Apr 08 '17 at 17:04
  • @BoPersson Oh, so is it because it's a const that I can't return a reference? – Thomas Phan Apr 08 '17 at 17:06

1 Answers1

0

You have only declared your A::length static member. You need to additionally define it in one, and only one, cpp file.

// in a cpp file
#include "a.hpp" // declaration is here (the code you posted)

int A::length = 5; // this, the definition, is also needed.

see for example this.

jpmag
  • 91
  • 1
  • 4
  • Sorry, maybe I don't understand how static variables work, but I thought with an integral type you can both declare and define the variable inside the header file. It's only with non-integral type that you have to declare it inside the class and define it outside. – Thomas Phan Apr 08 '17 at 16:31