0

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.

ildjarn
  • 59,718
  • 8
  • 115
  • 201
Lanaru
  • 7,862
  • 6
  • 31
  • 62
  • 1
    Possibly [relevant question](http://stackoverflow.com/questions/2479784/exporting-static-data-in-a-dll)? – tmpearce Aug 27 '12 at 21:01

1 Answers1

1

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.

Luchian Grigore
  • 236,802
  • 53
  • 428
  • 594
  • [This](http://social.msdn.microsoft.com/Forums/en/vclanguage/thread/e6badd8c-434a-4c5b-b5c2-1d58f4b5dd81) suggests you can't export data, just functions. Has this changed? – tmpearce Aug 27 '12 at 21:05
  • @tmpearce the op can test this and let us know. To me, that link seems weird, but then again it wouldn't be the first time I'd be wrong :) – Luchian Grigore Aug 27 '12 at 21:09