静态字段 - 初始化和更改值

发布于 2024-09-25 21:12:40 字数 500 浏览 0 评论 0原文

给定文件:

// file: q7a.h
static int err_code = 3;
void printErrCode ();
///////////// END OF FILE /////////////////
// file: q7a.c
#include <stdio.h>
#include "q7a.h"
void printErrCode ()
{
printf ("%d ", err_code);
}
///////////// END OF FILE /////////////////
// file: q7main.c
#include "q7a.h"
int main()
{
err_code = 5;
printErrCode ();
return 0;
}
///////////// END OF FILE /////////////////

输出是:

3

我的问题是为什么输出不是 5? 谢谢。

Given the files:

// file: q7a.h
static int err_code = 3;
void printErrCode ();
///////////// END OF FILE /////////////////
// file: q7a.c
#include <stdio.h>
#include "q7a.h"
void printErrCode ()
{
printf ("%d ", err_code);
}
///////////// END OF FILE /////////////////
// file: q7main.c
#include "q7a.h"
int main()
{
err_code = 5;
printErrCode ();
return 0;
}
///////////// END OF FILE /////////////////

The output is:

3

My Question is why the output is not 5?
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风铃鹿 2024-10-02 21:12:40

静态全局对象的范围仅限于当前编译单元。在这种情况下,您有两个编译单元,每个 .c 文件一个,每个编译单元都有自己的 err_code。

static global objects have scope limited to the current compilation unit. In this case you have two compilation units, one for each .c file, and each one has its own err_code.

迷迭香的记忆 2024-10-02 21:12:40

err_codestatic 关键字指定静态链接,即变量对于翻译单元来说是本地的。

当您分别编译文件 q7a.cq7main.c 时,将会有两个不同的 err_code 变量。因此,q7a.c 中的函数 printErrCode 使用仅在 q7a.c 范围内可见的 err_code

The static keyword for err_code specifies static linkage, i.e. the variable is local to the translation unit.

As you're compiling files q7a.c and q7main.c separately, there will be two different err_code variables. Hence the function printErrCode in q7a.c is using err_code visible only within the q7a.c scope.

夏の忆 2024-10-02 21:12:40

输出不是 5,因为全局变量不好

试试这个,不要在任何地方声明 err_code 并替换 main() 中的调用:

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

int main ()
{
    /* ... */
    printErrCode(5);
    /* ... */
}

The output is not 5, because global variables are bad.

Try this, without declaring err_code anywhere and replacing the call in main():

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

int main ()
{
    /* ... */
    printErrCode(5);
    /* ... */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文