4

文件()中C99写入const int x = 1;与写入时有什么区别吗?static const int x = 1;*.h

4

2 回答 2

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函数的前缀。

于 2012-06-22T08:33:44.090 回答
2

正如 cdarke 所说,它有所作为。

const int x = 1;为包括您的 h 文件在内的每个模块创建链接器可见符号。
然后链接器应该停止并出现错误,因为同一符号有多个(可见)定义。

static const int x = 1;为每个模块(包括您的 h 文件)创建一个变量但没有链接器符号。
链接器可以链接代码,但是当您创建多个同名变量实例时,不确定您的代码是否按预期工作。

顺便提一句。在 h 文件中定义变量绝对是个坏主意,标准方法是在 c 文件中定义它们,并且只在 h 文件中声明它们(如果你真的需要访问它们)。

当您static只想在一个模块中使用变量时使用,并且它应该对所有其他模块不可见。
const ...仅当您确实需要从另一个模块访问它时,但恕我直言,您通常应该避免使用全局可访问变量。

我的文件.c

#include "myFile.h"
const int x=1;
static const int y=2;

我的文件.h

extern const int x;
于 2012-06-22T08:49:08.413 回答