gpt4 book ai didi

c - 外部变量的值

转载 作者:行者123 更新时间:2023-11-30 18:41:22 25 4
gpt4 key购买 nike

我正在用 C 语言进行固件编程。

我有一个头文件:extern.h:

extern int x;

我有file1.c:

#include"extern.h"
//----------foo1 gives value to x------------------------

foo1(void)
{
int x=200;
}

现在我在 file2.c 中有 foo2

#include"extern.h"

foo2(void)
{
int x;
printf("%d",x);
}

最后在main.c

#include"extern.h"

void main()
{
foo1();
foo2();
}

如果在执行中获取垃圾值可能会出现什么问题?我相信变量的值必须是 200。

我通过 mplab c18 做了类似的事情,而不是 foo2.c 中的 printf,我在foo2.c 它显示了数千和万的随机 int 值..与我给出的 200 完全不相关。

当我将“x”初始化为

   foo2(void)
{
int x;
}

它再次显示以千为单位的随机值。

我相信这不是我所做的编码的问题,因为它必须传输 200。

注意:

But on counter of that if initialize and transmit in foo2.c then the values are displayed correctly.

我应该在哪里寻找错误:在 GUI 中还是在固件中?

最佳答案

当您说 extern int x 时,这意味着它是一个全局变量,将在其他 .c 文件中定义。在 foo1 和 foo2 中定义的局部变量优先于全局 extern 变量。在 foo1 中,x 的值将为 200,而在 foo2 中,x 的值可以是任何值,具体取决于堆栈上的内容。另外,我不知道您在哪里实际将 x 定义为全局变量。这也不见了。

关于c - 外部变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com