将变量放入标头与将变量放入源之间的区别 [英] Difference between putting variables in header vs putting variables in source

查看:20
本文介绍了将变量放入标头与将变量放入源之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我声明了一个带有变量的头文件:

Say I declare a header file with a variable:

int count;

然后在源文件中,我要使用count.我是否必须将其声明为:

Then in the source file, I want to use count. Do I have to declare it as:

extern int count

或者我可以在我的源文件中使用它吗?假设我有 #include "someheader.h".还是我应该在源文件中声明它?count放在头文件和源文件有什么区别?还是没关系?

Or can I just use it in my source file? All assuming that I have #include "someheader.h". Or should I just declare it in the source file? What is the difference between putting count in the header file vs the source file? Or does it not matter?

推荐答案

你只需要一个 count 变量,对吧?那么这一行:

You only want one count variable, right? Well this line:

int count;

为您定义一个 count 变量.如果您将其粘贴在多个文件中(通过将其包含在标题中),那么您将有多个 count 变量,每个文件一个,并且您会收到错误,因为它们都有同名.

Defines a count variable for you. If you stick that in multiple files (by including it in a header), then you'll have multiple count variables, one for each file, and you'll get errors because they'll all have the same name.

extern 关键字所做的只是说在其他文件中定义了一个 count 变量,我们只是让编译器知道它,以便我们可以在这个文件中使用它.所以 extern 声明是你想要放在你的头文件中以包含在你的其他文件中的东西.将 int count; 定义放在 one 源文件中.

All the extern keyword does is say that there is a count variable defined in some other file, and we're just letting the compiler know about it so we can use it in this file. So the extern declaration is what you want to put in your header to be included by your other files. Put the int count; definition in one source file.

这篇关于将变量放入标头与将变量放入源之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆