变量定义应该在头文件中吗? [英] Should variable definition be in header files?

查看:298
本文介绍了变量定义应该在头文件中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C 的最基本的了解和编译过程最近变得生疏了.我试图找出以下问题的答案,但无法连接编译,链接和预处理阶段的基础知识.在Google上进行快速搜索也无济于事.因此,我决定寻求最终的知识来源:)

My very basic knowledge of C and compilation process has gone rusty lately. I was trying to figure out answer to the following question but I could not connect compilation, link and pre-processing phase basics. A quick search on the Google did not help much either. So, I decided to come to the ultimate source of knowledge :)

我知道:不应在.h文件中定义变量.可以在此处声明它们.

I know: Variables should not be defined in the .h files. Its ok to declare them there.

原因:由于头文件可能会从多个位置包含在内,因此多次重新定义了变量(Linker给出了错误).

Why: Because a header file might get included from multiple places, thus redefining the variable more than one time (Linker gives the error).

可能的解决方法:在头文件中使用头保护,并在其中定义变量.

Possible work-around: Use header-guards in header files and define variable in that.

这真的是一个解决方案:否.因为标头保护符用于预处理阶段.那是告诉编译器该部分已经被包含,不再包含它.但是我们的多重定义错误出现在链接器部分-编译后很久.

Is it really a solution: No. Because header-guards are for preprocessing phase. That is to tell compiler that this part has been already included and do not include it once again. But our multiple definition error comes in the linker part - much after the compilation.

这件事使我对预处理和如何处理感到困惑.链接工作.我认为,如果已定义标头保护符号,则预处理将仅不包括代码.在那种情况下,变量问题的多重定义难道也不能解决吗?

This whole thing has got me confused about how preprocessing & linking work. I thought that preprocessing will just not include the code, if the header guard symbol has been defined. In that case, shouldn't multiple definition of a variable problem also get solved?

这些预处理指令将如何避免在头文件保护下重新定义符号,从而节省了编译过程,但是链接器仍然获得了该符号的多个定义?

What happens that these preprocessing directives save the compilation process from redefining symbols under header guards, but the linker still gets multiple definitions of the symbol?

推荐答案

标题防护可保护您免受单个源文件中的多个包含,而不是多个源文件的影响.我想您的问题源于对这一概念的不了解.

Header guard protects you from multiple inclusions in a single source file, not from multiple source files. I guess your problem stems from not understanding this concept.

并不是在编译期间由于这个问题而保存了预处理器防护措施.实际上,在编译期间,只有一个源文件被编译为obj,符号定义未解析.但是,在链接器尝试解析符号definitons的情况下,看到不止一个定义导致其标记错误的定义会引起混乱.

It is not that pre-processor guards are saving during the compile time from this problem. Actually during compile time, one only source file gets compiled into an obj, symbol definitions are not resolved. But, in case of linking when the linker tries to resolve the symbol definitons, it gets confused seeing more than one definition casuing it to flag the error.

这篇关于变量定义应该在头文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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