2

I have this class that has a static member. it is also a base class for several other classes in my program. Here's its header file:

#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP

namespace yarlObject
{
    class YarlObject
    {
    // Member Variables
        private:
            static int nextID; // keeps track of the next ID number to be used
            int ID; // the identifier for a specific object

    // Member Functions
        public:
            YarlObject(): ID(++nextID) {}
            virtual ~YarlObject() {}

            int getID() const {return ID;} 

    };
}

#endif

and here's its implementation file.

#include "YarlObject.hpp"

namespace yarlObject
{
    int YarlObject::nextID = 0;
}

I'm using g++, and it returns three undefined reference to 'yarlObject::YarlObject::nextID linker errors. If I change the ++nextID phrase in the constructor to just nextID, then I only get one error, and if I change it to 1, then it links correctly. I imagine it's something simple, but what's going on?

2
  • 99.9% sure, Since it links correctly when I change ++nextID to 1.
    – Max
    Commented May 26, 2010 at 21:06
  • 1
    if you don't reference nextID then you don't need to define it. So that's not an indication for the presence of that definition in the final executable. In fact, the fact that it works is an indicate that you do miss to link against the implementation file. Commented May 26, 2010 at 22:03

1 Answer 1

1

Make sure you are linking against the generated .o file. Double-check the makefile.

4
  • 1
    Why should this make any difference? I got the same errors as @Max if I didn't link against the YarlObject.o file and they all went away when I did link it (with the inline constructor).
    – Troubadour
    Commented May 26, 2010 at 21:26
  • -1: While this may have fixed the problem for @Max it most certainly is not for the reason you state.
    – Troubadour
    Commented May 26, 2010 at 21:39
  • 1
    I double checked my makefile, and it turned out I had forgotten to update it with YarlObject.o. Thanks for catching it, and apologies to the person who first mentioned it for not believing him. This is why I never say I'm 100% sure about anything in programming. I'm almost always immediately proven wrong. :)
    – Max
    Commented May 26, 2010 at 21:52
  • I know @litb suggested we cancel our downvotes (although his comment is now gone) but really it was someone else that pointed out that the .o file was not being linked against. Editing the answer to say that now doesn't make me feel any need to give you credit for it. In fact writing "Double-check the makefile" after @Max commented that he double-checked the makefile makes me wish I could downvote twice.
    – Troubadour
    Commented May 26, 2010 at 22:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.