声明变量在头文件 - 静态或不是? [英] Variable declarations in header files - static or not?

查看:138
本文介绍了声明变量在头文件 - 静态或不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在重构远一些 #define语句我碰到类似于一个C ++头文件下面的声明来了:

When refactoring away some #defines I came across declarations similar to the following in a C++ header file:

static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;

现在的问题是,有什么区别,如果有的话,将静态化妆?注意头的多个包容是不可能的,因为经典的的#ifndef头文件 #定义页眉 #ENDIF 绝招(如果该事项)。

The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic #ifndef HEADER #define HEADER #endif trick (if that matters).

请问静态平均创建 VAL 只有一个副本,以防头部被多个源文件包含?

Does the static mean only one copy of VAL is created, in case the header is included by more than one source file?

推荐答案

静态意味着将有VAL的一个副本创建为每个源文件被列入,但同时也意味着多个夹杂物不会导致多VAL定义将在链接时发生碰撞。如果没有静态,你需要确保只有一个源文件中定义VAL而另一个源文件中声明它的extern。通常人们会通过在一个源文件(用初始化可能)定义它做到这一点,把extern声明在头文件。

The static means that there will be one copy of VAL created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of VAL that will collide at link time. Without the static you would need to ensure that only one source file defined VAL while the other source files declared it extern. Usually one would do this by defining it (possibly with an initializer) in a source file and put the extern declaration in a header file.

在全球范围内的静态变量只在自己的源文件中可见他们是否到了那里通过一个包含或分别在主文件。

static variables at global level are only visible in their own source file whether they got there via an include or were in the main file.

顺便说一句,这是用C继承了的C ++功能。它不是特定于C ++

By the way, this is a feature of C inherited by C++. It is not specific to C++.

这篇关于声明变量在头文件 - 静态或不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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