“extern”的问题关键词
我在 cpp 文件中有一组全局变量和一个方法。
int a;
int b;
int c;
void DoStuff()
{
}
在头文件中,我已经使用 extern 关键字显式声明了它们。我的问题是,当我将头文件包含在另一个 C++ 文件中时,我无法使用外部变量和方法。它给出了一个链接器错误,指出方法和变量的错误LNK2001:无法解析的外部符号。我在这里做错了什么?
PS:DoStuff() 方法填充变量。所有头文件和cpp文件都在同一个项目文件夹中。
谢谢你!
I have a set of global variables and a method in a cpp file.
int a;
int b;
int c;
void DoStuff()
{
}
in the header file I have declared them explicitly with the extern keyword. My problem is when I include the header file in another C++ file, I can't use the external variables and the method. It's giving a linker error saying error LNK2001: unresolved external symbol for the methods and variables. What have I done wrong here??
PS: DoStuff() method populates the variables. All the header files and cpp files are in the same project folder.
Thank You!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
在标头中定义这些变量,而不仅仅是声明它们。
extern int x;
只是一个声明(不是定义)简单示例
a.cpp
b.cpp
Try this
Define those variables inside your header instead of just declaring them.
extern int x;
is just a declaration(not a definition)Simple example
a.cpp
b.cpp
您必须在编译集中包含 .cpp 文件,该文件定义了这些
extern
变量以及在标头中声明的函数。如果包含定义的 .cpp 文件未针对使用头文件中的声明的文件进行编译和链接,您将收到链接器错误。You must include the .cpp file which defines those
extern
variables and the function declared in your header in the compilation set. If the .cpp file containing the definitions is not compiled and linked against one which uses the declarations from your header file, you will get linker errors.您确定要链接到与包含方法和变量的源文件相对应的目标文件吗?
Are you sure you're linking in the object file that corresponds to the source file containing your methods and variables?
由于您使用的是 Visual-C++(根据标签),因此我只需确保编译时所有文件都位于同一个项目中。确保您正在构建项目而不仅仅是构建文件。
我怀疑情况确实如此,但您可能还想检查源文件是否编译为 C 或 C++,否则您可能会在命名方案方面遇到一些麻烦。
Since you are using Visual-C++ (according to the tag), I'd just make sure that all your files are in the same project when compiling. Make sure you are building project and not just building a file.
I doubt this is the case, but you also might want to check that the source files are either compiled as C or as C++, or you might get into some trouble with the naming scheme.