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

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

问题描述

我是 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
", 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),则链接器将给出错误定义两次相同的 var?

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 插入到静态变量中(毕竟它是静态和全局的)?

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天全站免登陆