在标头(C99
)文件中写const int x = 1;
与static const int x = 1;
时,*.h
会有什么不同吗?
答案 0 :(得分:3)
是。首先,我不建议您将这些定义放在头文件中,但如果这样做,则取决于头文件的包含位置。无论如何,static
使变量成为当前程序单元的本地变量。这是一个例子:
mp1.c:
#include <stdio.h>
void myfunc(void);
const int x = 1;
int main (int argc, char *argv[])
{
printf ("main: value of x: %d\n",x);
myfunc();
return 0;
}
mp2.c:
#include <stdio.h>
extern int x;
void myfunc(void)
{
printf ("myfunc: value of x: %d\n",x);
}
汇编:
gcc -o mp mp1.c mp2.c
工作正常。现在将mp1.c更改为使用static const int x = 1;
,当我们编译时(实际上是链接错误),我们得到:
home/user1> gcc -o mp mp1.c mp2.c
/tmp/ccAeAmzp.o: In function `myfunc':
mp2.c:(.text+0x7): undefined reference to `x'
collect2: ld returned 1 exit status
变量x在mp1.c之外不可见。
这同样适用于函数的static
前缀。
答案 1 :(得分:2)
正如cdarke所说,它有所不同。
const int x = 1;
为每个模块(包括您的h文件)创建链接器可见符号
链接器应该因错误而停止,因为同一符号有多个(可见)定义。
static const int x = 1;
为包含h文件的每个模块创建一个变量但没有链接符号
链接器可以链接代码,但是当您创建具有相同名称的变量的多个实例时,它不确定您的代码是否按预期工作。
顺便说一下。在h文件中定义变量是一个绝对坏主意,标准方法是在c文件中定义它们,并且只在h文件中声明它们(如果你真的需要访问它们)。
当您只想在一个模块中使用变量时,使用static
,并且它应该对所有其他模块都不可见。
const ...
只有当你真的需要从另一个模块访问它时,恕我直言,你通常应该避免使用全局可访问的变量。
<强> myfile.c文件强>
#include "myFile.h"
const int x=1;
static const int y=2;
<强> myFile.h 强>
extern const int x;