公众号:嵌入式不难
本文仅供参考学习,如有错误之处,欢迎留言指正。
一、变量/常量说明
1.定义说明
- 全局定义
- 变量 global_temp
- 静态变量 global_temp_static
- 常量 global_const
- 静态常量 global_const_static
- 局部定义
- 变量 local_temp
- 静态变量 local_temp_static
- 常量 local_const
- 静态常量 local_const_static
2.实现方案
-
步骤1:按上述说明写函数,定义变量和函数,代码如下
int global_temp; static int global_temp_static; const int global_const = 1; static const int global_const_static = 2; /*以下变量用于存储变量的地址*/ int global_temp_adress; int global_temp_static_adress; int global_const_adress; int global_const_static_adress; int local_temp_adress; int local_temp_static_adress; int local_const_adress; int local_const_static_adress; int main(void) { int local_temp; static int local_temp_static; const int local_const = 3; static const int local_const_static = 4; global_temp_adress = (int)&global_temp; global_temp_static_adress = (int)&global_temp_static; global_const_adress = (int)&global_const; global_const_static_adress = (int)&global_const_static; local_temp_adress = (int)&local_temp; local_temp_static_adress = (int)&local_temp_static; local_const_adress = (int)&local_const; local_const_static_adress = (int)&local_const_static; while(1); }
-
步骤2:进入仿真,通过Watch窗口查看变量的值以查看变量地址
-
步骤3:查看.map文件内存分布情况
STACK 0x20000030 Section 1024 startup_stm32f103xb.o(STACK) __initial_sp 0x20000430 Data 0 startup_stm32f103xb.o(STACK)
二、变量/常量位置分析
1.首先梳理编译完以后RAM和Flash空间分布情况
- RAM分布
- 0x2000 0000 – 0x2000 0030 为全局变量的分布空间(这个空间的分布大小是根据程序中一些变量的定义情况来决定的,编译时确定起始和结束地址)
- 0x2000 0030 – 0x20000430为栈空间,这个空间的大小是人为确定大小的,即是.s文件中Stack_Size的值,在此例中Stack_Size的值为0x400,而起始地址由上一空间的结束地址决定
- 0x20000430 – xxxx xxxx为堆空间(起始地址紧接上一空间结束地址),空间大小人为确定
- Flash分布,0x0800 0000开始为Flash空间
- 第一段,存储栈的结束地址和中断函数入口
- 第二段,存储代码
- 第三段,存储常量
2.根据上述区域进行对号入座
- RAM空间
- 0x2000 0000 – 0x2000 0030全局变量数据段
- global_temp --> 0x2000 0000
- global_temp_static --> 0x2000 0004
- local_temp_static --> 0x2000 0028
- 0x2000 0030 – 0x20000430栈空间(向下生长)
- local_temp --> 0x2000 0428
- local_const --> 0x2000 0424
- 0x2000 0000 – 0x2000 0030全局变量数据段
- Flash空间
- 第三段
- global_const --> 0x0800 0258
- global_const_static --> 0x0800 025C
- local_const_static --> 0x0800 0260
- 第三段
三、结论
- 进入全局变量RAM数据段的特点
- 一定为变量(但不是所有变量进入此段)
- 所有全局变量(不管是静态的还是非静态的,统一进入全局变量数据段),地址唯一占有
- 函数内的局部变量,仅定义为静态属性时可进入全局变量数据段,地址唯一占有
- 进入栈空间的特点(在退出函数时系统会回收此函数内申请的栈)
- 一定为非静态变量
- 函数内部定义的变量或常量
- 进入Flash空间特点
- 一定为常量(但不是所有的常量都会进入Flash空间)
- 所有全局常量(不管是静态的还是非静态的),地址唯一占有
- 函数内的局部常量(仅定义为静态属性时可进入Flash空间)