C51之局部变量和全局变量小记

2019-04-15 15:12发布

若在C51中定义一个全局变量,编译器将在RAM中为该变量指定一个专用地址,在C程序中给变量赋的值将存入这个专用地址中,程序操作该变量是,首先从专用地址中取出存放的值,然后再进行计算。全局变量被定义在内存中的专门地址上,存储位置固定。对于频繁存取的重要变量但可以采用全局变量以减少代码的长度;由于全局变量总是占用内存,如果过多,或者把程序处理和计算中的一些中间变量也定义为全局变量,将大大消耗内存空间,处理速度会变慢,同时数据安全性也会降低。 C51中定义一个的局部变量可以和全局变量同名,但在这种情况下,局部变量的优先级较高,而同名的全局变量在该功能模块内暂时被屏蔽。 若在C51中定义一个局部变量,编译器会将该变量的地址分配到寄存器组R0~R7中。由于他是局部变量,所以编译器将使用立即数赋值语句为代表该变量的寄存器Rn赋值,最后的计算结果也将存在寄存器组中,位置有编译器任意指定。局部变量由于用寄存器直接操作,存取速度和计算机速度都很快;由于寄存器数量有限,若局部变量过多,将会使代码由于频繁分配寄存器而变得冗长。
Global variables you create in your C programs are stored in the memory area specified or in the default memory area implied by the memory model. The assembly label for the variable is the variable name. For example, for the following global variables: unsigned int bob; unsigned char jim; the compiler generates the following assembler code: ?DT?MAIN SEGMENT DATA PUBLIC jim PUBLIC bob RSEG ?DT?MAIN bob: DS 2 jim: DS 1 ; unsigned int bob; ; unsigned char jim; To access these variables in assembler, you must create an extern declaration that matches the original declaration. For example: EXTERN DATA(jim) If you use in-line assembler, you may simply use C extern variable declarations to generate the assembler EXTERN declarations. You may access global variables in assembler using their label names. For example: MOV A,jim Note
  • Type information is not transmitted to your assembler routines. Assembly code must explicitly know the type of the global variable and the order in which it is stored.
  • The EXTERN definitions for a C external variable are generated only if the variable is referenced by the C code in the module. If an external variable is only referenced by in-line assembly code, you must declare them in in-line assembly code within that module.
reference:http://www.keil.com/support/man/docs/c51/c51_ap_globalvars.htm http://www.kar.elf.stuba.sk/predmety/mmp/c51/c02.htm http://www.kar.elf.stuba.sk/predmety/mmp/c51/c51prim.htm