C++标准中的$ 7.3.1.1/2节描述如下:
在声明命名空间作用域中的对象时,不推荐使用static关键字; unnamed-namespace提供了一个更好的选择.
我不明白为什么一个未命名的命名空间被认为是一个更好的选择?理由是什么?我已经知道标准的内容很长一段时间,但我从未认真考虑过,即使我回答这个问题:未命名的命名空间优于静态?
它是否被认为是优越的,因为它也可以应用于用户定义的类型,正如我在回答中所描述的那样?还是有其他原因,我不知道?我问这个问题,特别是因为这是我在答案中的推理,而标准可能会考虑其他因素.
如果我有一个如下所示的C文件,i和之间有什么区别j?
#include <stdio.h>
#include <stdlib.h>
static int i;
int j;
int main ()
{
//Some implementation
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试一个小例子来了解静态外部变量及其用途.静态变量属于局部范围,外部变量属于全局范围.
static5.c
#include<stdio.h>
#include "static5.h"
static int m = 25;
int main(){
func(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
static5.h
#include<stdio.h>
int func(val){
extern int m;
m = m + val;
printf("\n value is : %d \n",m);
}
Run Code Online (Sandbox Code Playgroud)
gcc static5.c static5.h
o/p:
static5.c:3: error: static declaration of m follows non-static declaration
static5.h:3: note: previous declaration of m was here
Run Code Online (Sandbox Code Playgroud)
EDITED
正确的程序:
a.c:
#include<stdio.h>
#include "a1_1.h"
int main(){
func(20);
return 0;
}
a1.h:
static int i = 20;
a1_1.h:
#include "a1.h"
int func(val){
extern …Run Code Online (Sandbox Code Playgroud) 举个例子:
// myheader.h
static int myStaticVar = 0;
// If we remove 'static' the compiler will throw linker error.
void DoStuff();
// and myheader.cpp, and main.cpp; etc
Run Code Online (Sandbox Code Playgroud)
这就是我解释它的方式:
静态变量没有外部链接,当我们编译没有'static'时,我们在每个文件中"包含"静态变量(这里是全局的),这会创建重复项,并且链接器将抛出错误,因为不允许多次声明.
有没有更好的方法来解释这个?谢谢.
PS:我们假设在头文件中有静态变量(不是在谈论成员)吗?