views:

234

answers:

1

Hi. 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  A: 

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

Matt Davis
This fixed it. Thanks.
Max
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
-1: While this may have fixed the problem for @Max it most certainly is not for the reason you state.
Troubadour
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
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