[英]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. 我的Visual Studio C ++解决方案中有两个项目,我想在它们之间共享一些代码。 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). 1)使用名为Project1的空项目创建空的Visual Studio解决方案,将其类型更改为“静态库”(lib)。 Add Foo class: 添加Foo类:
Foo.h: foo.h中:
#pragma once
class Foo
{
public:
static int F(int a);
private:
static int bar;
};
Foo.cpp: Foo.cpp中:
#include "Foo.h"
int Foo::F(int a)
{
bar = 3;
return a*bar;
}
2) Create empty project named Project2. 2)创建名为Project2的空项目。
Source.cpp: 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" 3)在Project2的属性中,将Project1文件夹添加到“其他包含目录”
4) In Common Properties of Project2, click "Add new reference" add Project1 as a new reference. 4)在Project2的Common Properties中,单击“Add new reference”,将Project1添加为新引用。 (or you can add Project1.lib it in Linker -> Input -> Additional Dependencies). (或者您可以在链接器中添加Project1.lib - >输入 - >附加依赖项)。
Now, when you compile only static library (Project1), it works. 现在,当您只编译静态库(Project1)时,它可以工作。 When you compile both or just your executable (Project2), you got 当你编译两个或只是你的可执行文件(Project2)时,你得到了
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)? 是否有更好的方法和简单的方法在项目之间共享代码(而不是仅仅将相同的.cpp / .h文件包含在两个项目中)?
You have declared bar
in Foo
but you haven't provided a definition for it. 您已在Foo
声明了bar
,但您尚未为其提供定义。 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 如果您想用特定值(比如42)初始化它,您可以这样做
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. 你只得到Project1
的链接器错误的原因是因为静态库和Project2
都没有实际访问 Foo::bar
所以没有引用它来供链接器解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.