访问全局变量给出垃圾值

Accessing global variable give junk values

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

处理器 - Intel 80486

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

uint32_t unGlobal = 0xABCDEF90;

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

    UartWrite (unLocal);
    UartWrite (unGlobal);
}

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

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

参数type in the prototype for UartWrite may not be sufficient size to contain the value for your global. I do not have the prototype, but for similar函数(不同库无疑),参数类型为char。如果它在您的原型中也是 char,那么为 unsigned int 传递一个值可能是您问题的根源。

下面说明了这样一种情况:函数接受的变量对于原型来说太大而没有错误,但随后会产生意外结果:

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

Post UartWrite (??? ) 的原型;

编辑(新信息)

我发现 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关键字volatile表示"that a value may change between different accesses, even if it does not appear to be modified"。试试这个,看看它是否适合你。

问题出在静态初始化上。因为在 运行 时间重新初始化全局变量会给出正确的值。 感谢 ryyker、@Lundin 和所有