Thread: C++ public: static field error

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    9

    C++ public: static field error

    I'm trying to create a public and static filed in a class called ResourceManager. But when trying to access the field even from inside the class it wont work. I'm getting this error message:

    Error 1 error LNK2001: unresolved external symbol "public: static int ResourceManager::num" (?num@ResourceManager@@2HA)

    Here's my code:

    ResourceManager.h


    Code:
        class ResourceManager
        {
            public:
                static int num;
                static void loadContent();
        };
    ResourceManager.cpp




    Code:
    #include "ResourceManager.h"
    
    
    void ResourceManager::loadContent()
    {
        num = 0;
    }
    I'm using Visual Studio 2012.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Static variables need to be defined (exactly once in your program). Your code declares it (tells the compiler it exists and what type it is) but does not define it (make it exist).

    Add this line to your ResourceManager.cpp after the #include "ResourceManager.h" line, at file scope.
    Code:
    int ResourceManager::num = 0;
    The initialisation to zero is optional (as it is the default for static ints).

    Don't place that line in the header file as, if the header file is #include'd by more than one source file, it will be multiply defined. That is a violation of the "one definition rule" according to the standard. Practically, it usually results in the linker complaining about a multiply defined symbol, rather than an unresolved (or undefined) one.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Apr 2014
    Posts
    9
    Ok thank you

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. error: object ref. required for non static field
    By Dale in forum C# Programming
    Replies: 3
    Last Post: 11-10-2011, 10:48 AM
  2. Replies: 2
    Last Post: 06-07-2009, 08:49 AM
  3. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  4. Get data from a .txt file field by field...
    By IndioDoido in forum C Programming
    Replies: 5
    Last Post: 10-19-2007, 06:07 PM
  5. error: field has incomplete type
    By kris.c in forum C Programming
    Replies: 11
    Last Post: 06-12-2007, 03:53 PM

Tags for this Thread