简体   繁体   中英

How to share 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 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)?

You have declared bar in Foo but you haven't provided a definition for it. You need to add the following to your code.

int Foo::bar;

If you would like to initialize it with 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 access Foo::bar so there are no references to it for the linker to resolve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM