gpt4 book ai didi

c - 访问全局变量给出垃圾值

转载 作者:行者123 更新时间:2023-11-30 19:15:44 24 4
gpt4 key购买 nike

我尝试使用以下 C 代码通过 UART 打印变量。

处理器 - Intel 80486

编译器 - IC 编译器(来自 Intel,1990 年发布)

uint32_t unGlobal = 0xABCDEF90;

void main (void)
{
uint32_t unLocal = 0x12345678;

UartWrite (unLocal);
UartWrite (unGlobal);
}

UartWrite()是串口驱动程序。 UartWrite 的参数是 32 位,并且在内部打印每个字符。

这里,局部变量打印正确,但打印全局变量却给出垃圾值!可能是什么原因导致无法获取全局变量的值。有人可以帮我解决这个问题吗?

最佳答案

参数 type 在 UartWrite 原型(prototype)中可能没有足够的大小来包含全局值。我没有原型(prototype),但对于 similar 函数(毫无疑问是不同的库),参数类型是char。如果原型(prototype)中也是 char,那么传递 unsigned int 的值可能是问题的根源。

下面说明了这样一种情况:函数接受一个对于原型(prototype)来说太大的变量而不会出现错误,但随后可能会产生意外的结果:

int func(char a)
{
a = 10000;
return a;
}

int main(void)
{
int a = 10000;
int b;
b = func(a);// note int type, or 10000 does not fit into a char type
// b is returned, but not with the expected value.
printf("%d" b);
return 0;
}

结果:b = -24

发布UartWrite (???)的原型(prototype)

编辑(新信息)

我发现 this Intel document on a compiler released in 1990 这可能是您正在使用的编译器的近亲。查看从第 68 页开始的部分:

Each global symbol definition or reference in a compilation unit has a visibility attribute that controls how (or if) it may be referenced from outside the component in which it is defined. There are five possible values for visibility:
• EXTERNAL – The compiler must treat the symbol as though it is defined in another component. For a definition, this means that the compiler must assume that the symbol will be overridden (preempted) by a definition of the same name in another component. See Symbol Preemption. If a function 69 symbol has external visibility, the compiler knows that it must be called indirectly and can inline the indirect call stub.
• DEFAULT – Other components can reference the symbol. Furthermore, the symbol definition may be overridden (preempted) by a definition of the same name in another component.
• PROTECTED – Other components can reference the symbol, but it cannot be preempted by a definition of the same name in another component.
• HIDDEN – Other components cannot directly reference the symbol. However, its address might be passed to other components indirectly (for example, as an argument to a call to a function in another component, or by having its address stored in a data item reference by a function in another component).
• INTERNAL – The symbol cannot be referenced outside its defining component, either directly or indirectly.

再往下一点例如:

int i __attribute__ ((visibility("default")));
void __attribute__ ((visibility("hidden"))) x () {...}
extern void y() __attribute__ ((visibilty("protected");

还有更多内容。希望这会有所帮助。

关于c - 访问全局变量给出垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948892/

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