1

I'm trying to make a text-based console video game in c++.

I have an Inventory class with a header and a source file. In the same header file I have declared a struct called STRINGSIZES with two integer members called name and description. They are used to store the length that should be used when displaying the Items, or from which length the name will be shortened. The header file "Inventory.h" looks something like this:

#pragma once
#include <iostream>

struct STRINGSIZES {    //the fixed Size with which Inventory lists will be printed
    int name;
    int description;
};

class Inventory
{
public:
    //some unrelated code
    Inventory();

    static void setStringSizes(int name, int description);
private:
    static STRINGSIZES stringSizes;
};

In the Inventory.cpp file, I define the setStringSizes() method like so:

void Inventory::setStringSizes(int name, int description)
{
    stringSizes.name = name;
    stringSizes.description = description;
}

In my main Source.cpp file, I am firstly calling this method.

Now when I try to compile this I get the errors:

1>Inventory.obj : error LNK2001: unresolved external symbol "public: static int stringSizeNames::name" (?name@stringSizeNames@@2HA)

1>Inventory.obj : error LNK2001: unresolved external symbol "public: static int stringSizeNames::description" (?description@stringSizeNames@@2HA)

What is the problem here?

joriba
  • 13
  • 3

1 Answers1

0

The error message refers to a variable which declaration you did not show in the question. But I think it is the same problem as with the static data member stringSizes.

Within the class definition this data member

static STRINGSIZES stringSizes;

is a declaration that is not a definition.

You have to define it outside the class definition in the cpp file for example like

STRINGSIZES Inventory::stringSizes;

If your compiler supports the C++17 Standard then you could define the data member inside the class definition the following way

class Inventory
{
    //...
    inline static STRINGSIZES stringSizes = {};
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • The first approach worked, thanks. The one with the `inline` keyword didn't, though I have no idea why as I'm using the newest Windows 10 SDK – joriba Mar 31 '20 at 10:33
  • @joriba If you are saying about MS Visual C++ then maybe you should set the project properties specifying the version of used C++. – Vlad from Moscow Mar 31 '20 at 10:37