I have two Projects in my Visual Studio C++ Solution and I want to share some code between them. So, I looked for it, and found that a lot of people suggested creating static library and linking it with both projects. However, when I do it, I got "unresolved external symbol" error for all static variables. Here how to reproduce the problem:
1) Create empty Visual Studio Solution with empty project named Project1, change it's type to "static library" (lib). Add Foo class:
Foo.h:
#pragma once
class Foo
{
public:
static int F(int a);
private:
static int bar;
};
Foo.cpp:
#include "Foo.h"
int Foo::F(int a)
{
bar = 3;
return a*bar;
}
2) Create empty project named Project2.
Source.cpp:
#include <iostream>
#include "Foo.h"
int main()
{
std::cout << Foo::F(2) << std::endl;
std::cin.get();
return 0;
}
3) In Properties of Project2, add Project1 folder to "Additional Include Directories"
4) In Common Properties of Project2, click "Add new reference" add Project1 as a new reference. (or you can add Project1.lib it in Linker -> Input -> Additional Dependencies).
Now, when you compile only static library (Project1), it works. When you compile both or just your executable (Project2), you got
2>Project1.lib(Foo.obj) : error LNK2001: unresolved external symbol "private: static int Foo::bar" (?bar@Foo@@0HA)
2>C:\dev\Project1\Debug\Project2.exe : fatal error LNK1120: 1 unresolved externals
If you remove static variable, it works. What am I doing wrong? Is there any better way and simple way to share code between projects (rather than just including same .cpp/.h files into both projects)?