I been trying to resolve this unresolved external symbol
on a static variable for hours now, and I'm at my wits' end. I'm using Visual Studio 2010. Here's a simplified overview of the situation:
Projects in question:
-ProjA (outputs a .dll and .lib)
-ProjB (outputs a .exe)
In ProjA, I have these two files:
//foo.h
#pragma once
class SUP
{
public:
static int staticint;
};
and
//foo.cpp
#include "foo.h"
int SUP::staticint = 10;
ProjB links to ProjA.lib
//main.cpp
#include "{Full_Path}foo.h"
int main(){
std::cout << SUP::staticint << std:: endl;
}
Now, main.cpp compiles without any problems, but when I try to build the project, I get the following error:
main.obj : error LNK2001: unresolved external symbol "public: static int SUP::staticint" (?staticint@SUP@@2HA)
I'm almost 100% certain I've set up ProjB's options correctly. Under "Additional Dependencies" all I have "ProjA.lib", and under "Additional Library Directories" I have the path to the directory where the ProjA.lib file is generated.
I've even had ProjA output a .map file, and in the map I find:
0003:00004458 ?staticint@SUP@@2HA 10049458 foo.obj
So I'm guessing that it means that staticint
has been defined correctly.
What could possibly be going wrong? Obviously, I'm doing something wrong, but I fail to see what. I've made sure that ProjB is linking with the correct .lib file. I've made sure the include directories are good. I've made sure that the definition of the static variable is sound. I will provide any other information if necessary.
Under MSVS you must explicitly declare the symbols you want exported with __declspec(dllexport)
.
Since SUP
is in a different library, only exported symbols will be available to other modules, which must mark them as __declspec(dllimport)
.
This dual behavior is usually achieve through a macro:
#ifdef EXPORT_MODULE
#define DLLIMPEXP __declspec(dllexport)
#else
#define DLLIMPEXP __declspec(dllimport)
#endif
and the class declared as
class DLLIMPEXP SUP
{
public:
static int staticint;
};
where EXPORT_MODULE
is defined in the project which exports the symbol.