把变量头VS把变量源之间的区别 [英] Difference between putting variables in header vs putting variables in source
问题描述
说我声明一个变量的头文件:
Say I declare a header file with a variable:
int count;
然后在源文件中,我想用计数
。我一定要其声明为:
extern int count
或者,我可以只使用它在我的源文件?所有假设我有的#includesomeheader.h
。或者我应该只是声明它的源文件? 是什么把计数
在头文件VS源文件之间的差异?或者它不要紧?
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?
推荐答案
您只需要一个计数
变量,对不对?嗯,这行:
You only want one count
variable, right? Well this line:
int 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
关键字则是说,有一个计数
在别的文件中定义的变量,我们'重新只是让编译器知道这一点,所以我们可以在这个文件中使用它。因此,的extern
的声明是要放在你的头怎么你的其他文件包括在内。把诠释计数;
定义的有一个源文件
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.
这篇关于把变量头VS把变量源之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!