在标头中初始化静态变量 [英] initializing a static variable in header

查看:92
本文介绍了在标头中初始化静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言编程的新手,所以我正在尝试许多不同的尝试,以使自己熟悉该语言.

I am new in programming in C, so I am trying many different things to try and familiarize myself with the language.

我写了以下内容:

文件 q7a.h :

File q7a.h:

static int err_code = 3;
void printErrCode(void);

文件 q7a.c :

File q7a.c:

#include <stdio.h>
#include "q7a.h"

void printErrCode(void)
{
        printf ("%d\n", err_code);
}

文件 q7main.c :

File q7main.c:

#include "q7a.h"

int main(void)
{
        err_code = 5;
        printErrCode();

        return 0;
}

然后我在makefile中运行以下命令(我正在使用Linux操作系统)

I then ran the following in the makefile (I am using a Linux OS)

gcc –Wall –c q7a.c –o q7a.o
gcc –Wall –c q7main.c –o q7main.o
gcc q7main.o q7a.o –o q7

输出为3.

为什么会这样?

如果您在头文件中初始化静态变量(实际上是任何变量),那么如果2个文件包含相同的头文件(在本例中为q7.c和q7main.c),则链接器将针对以下错误给出错误信息定义两次相同的变量?

If you initialize a static variable (in fact any variable) in the header file, so if 2 files include the same header file (in this case q7.c and q7main.c) the linker is meant to give an error for defining twice the same var?

为什么不将值5插入到静态var中(毕竟它是静态的和全局的)?

And why isn't the value 5 inserted into the static var (after all it is static and global)?

感谢您的帮助.

推荐答案

static表示该变量仅在编译单元内使用,不会暴露给链接器,因此如果您在目录中有static int头文件并将其包含在两个独立的.c文件中,您将拥有该int的两个离散副本,这很可能根本不是您想要的.

static means that the variable is only used within your compilation unit and will not be exposed to the linker, so if you have a static int in a header file and include it from two separate .c files, you will have two discrete copies of that int, which is most likely not at all what you want.

相反,您可以考虑extern int,然后选择一个实际定义它的.c文件(即仅int err_code=3).

Instead, you might consider extern int, and choose one .c file that actually defines it (i.e. just int err_code=3).

这篇关于在标头中初始化静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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