Landin Martens
Landin Martens

Reputation: 3333

C++ unresolved externals when calling static variable

I am trying to change a static variable inside a DLL, so when the extern function "ChangeVar" is called it will change the static variable. My problem is I can't get anything to compile. All of the code below is in a single C++ project compiled into a single DLL. I have no problems calling the function, as long as I don't try to change or get the static variable.

Static.h

class API
 {
   public:
     static int iValue;
 };

Functions.cpp

#include "Static.h"
extern "C"
{
    __declspec(dllexport) bool ChangeVar()
    {
        API::iValue = 0;
        if(API::iValue == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

When I do this I just two errors:

Error  1  error LNK2001: unresolved external symbol "public: static int API::iValue" (?iValue@API@@2HA)
Error  2  error LNK1120: 1 unresolved externals

What do I need to do to create a static variable (clearly my way does not work), and how would I modify it so that it works like static should, where its value will be changed in memory?

Upvotes: 2

Views: 716

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75130

This is answered by a SO C++ FAQ entry: you've declared the variable but not defined it. You have to add

int API::iValue = 0;

Somewhere in a source file to define it.

Also, your test

if (API::iValue == 0)

will always evaluate to true because you set it to 0 just before testing if it equals 0, and the function will always return true.

Upvotes: 1

Related Questions