How to split code between projects in Visual C ++ or "unresolved external symbol" for static variables in static lib
I have two projects in my Visual Studio C ++ Solution and I want to share some code with them. So I searched for it and found that a lot of people were suggesting creating a static library and linking to both projects. However, when I do this, I got an "unresolved external symbol" error for all static variables. Here's how to reproduce the problem:
1) Create an empty Visual Studio solution with an empty project named Project1, change it 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 an empty project called Project2.
Source.cpp:
#include <iostream>
#include "Foo.h"
int main()
{
std::cout << Foo::F(2) << std::endl;
std::cin.get();
return 0;
}
3) In the properties of Project2, add the Project1 folder to the "Additional Include Directories"
4) In the general properties of Project2 click "Add new link", add Project1 as a new link. (or you can add Project1.lib to Linker -> Input -> Additional Dependencies).
Now when you only compile the 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 the static variable it works. What am I doing wrong? Is there a better way and simpler way to share code between projects (instead of only including the same .cpp / .h files in both projects)?
source to share
You declared bar
in Foo
, but you did not provide a definition for it. You need to add the following to your code.
int Foo::bar;
If you want to initialize it to a specific value (say 42) you can do
int Foo::bar = 42;
The reason you only get a linker error for Project1
is because neither the static library nor Project2
actually Foo::bar
referenced, so there are no links for it.
source to share