块范围上没有链接? [英] No linkage at block scope?
问题描述
在块中声明的所有变量是否都没有链接?
例如:
1 :
如果我声明一个静态变量:
void foo )
{
static int i;
}
它有内部链接还是没有链接?
2:
如果我使用extern会发生什么? / p>
/ *全局范围* /
static int i;
void foo()
{
extern int i;
}
在这种情况下,
$ b
目标是生命周期管理:静态具有全局静态的生命周期,而它具有可见性(范围)。
注意
还通过将它们包含在匿名命名空间中来声明未链接的静态(全局)。这个技巧在标题库中常用:
命名空间/ * anon * /
{
void foo(){} //只在这个翻译单元
int answer = 42; // this too
}
extern
?
如果使用extern,声明为 extern
仅声明(没有定义)。因此,通常期望外部链接通过定义在另一翻译单元中定义。 (所以它的行为与在全局范围声明时相同)。这类似于局部函数声明:
int main()
{
void exit(int) ; //等于非本地声明
}
请注意, 2。
示例,变量 i
已声明 static
,因此不会得到外部链接。我可能会在另一个翻译单元中声明没有链接器冲突。
Do all variables declared in a block have 'no linkage'?
For example:
1:
If I declare a static variable:
void foo()
{
static int i;
}
Would it have an internal linkage or no linkage? If no linkage, then why make it static?
2:
What happens if I use extern?
/*global scope*/
static int i;
void foo()
{
extern int i;
}
In this case, what will be the linkage of i
?
Indeed, 'no linkage' at function scope.
The goal is lifetime management: the static has the lifetime of a global static, while it has the visibility (scope) of a local.
Note
In C++ you can also declare statics ('globals') without linkage by enclosing them inside an anonymous namespace. This trick is used commonly in header-only libraries:
namespace /*anon*/
{
void foo() {} // only in this translation unit
int answer = 42; // this too
}
What happens if I use
extern
?
If you use extern, the declaration is an extern
declaration only (nothing is defined). As such, it normally would be expected to external linkage by definition - being defined in another translation unit. (So it acts the same as if when it was declared at global scope). This is similar to local function declarations:
int main()
{
void exit(int); // equivalent to non-local declaration
}
Note that, in your 2.
example, variable i
was already declared static
and it will therefore not get external linkage. I might get declared in another translation unit without linker conflicts, though.
这篇关于块范围上没有链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!