外部变量 - 为什么?
我听说你不应该在头文件中定义任何东西,因为可能存在多个定义,但是如果你有包含防护,这种情况就不会发生,对吧?将 extern 添加到变量还有什么其他原因?
I've heard that you shouldn't define anything in header files, because of the possibility of multiple defines, but if you have include guards, this shouldn't happen, right? What other reasons are there for adding extern to variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
包含防护仅防止在单个 翻译单元(又名 < em>编译单元)。这并没有解决链接时来自不同翻译单元的多个定义的问题。因此,您应该只将声明放在头文件(.h)中,将定义放在源文件(.c)文件中。
Include guards merely prevent multiple inclusion of a header within a single translation unit (aka compilation unit). This does not address the problem of multiple definitions from separate translation units at link time. Hence you should only ever put declarations in header (.h) files, and definitions in source (.c) files.
当变量在一个源文件(更具体地说,一个翻译单元)中定义并在另一个源文件中引用时,您通常会在头文件中声明
extern
变量。You generally declare
extern
variables in header files when the variable is defined in one source file (more specifically, one translation unit), and referenced in another.