“extern”的问题关键词

发布于 2024-09-09 08:49:41 字数 313 浏览 1 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

來不及說愛妳 2024-09-16 08:49:41

尝试

在标头中定义这些变量,而不仅仅是声明它们。

extern int x; 只是一个声明(不是定义)

简单示例

a.cpp

 int a,b,c; //definition

 void doStuff(){ 

 }

b.cpp

extern int a,b,c; //extern keyword is mandatory
void doStuff();   //extern keyword is optional because functions by default have external linkage

int main()
{

   doStuff();
}

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

 int a,b,c; //definition

 void doStuff(){ 

 }

b.cpp

extern int a,b,c; //extern keyword is mandatory
void doStuff();   //extern keyword is optional because functions by default have external linkage

int main()
{

   doStuff();
}
翻身的咸鱼 2024-09-16 08:49:41

您必须在编译集中包含 .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.

七秒鱼° 2024-09-16 08:49:41

您确定要链接到与包含方法和变量的源文件相对应的目标文件吗?

Are you sure you're linking in the object file that corresponds to the source file containing your methods and variables?

烟酉 2024-09-16 08:49:41

由于您使用的是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文