c++中static变量的存储duration
程序员文章站
2022-07-01 23:25:21
...
c++中static变量的存储duration
static是c++中一个常见的关键字,当修饰全局变量和局部变量时会有不同的效果,同时变量声明初始化与否对生成的二进制文件也有影响。
写了一小段代码测试这些细节。
代码如下
#include<cstdio>
int gi;
int gii=1; //global int initialized
static int si;
static int sii=3;
int main(int argc,char** argv){
int li;
static int sli;
static int slii=4;
char *buf=new char[256];
printf("gi %p, gii %p, si %p, sii %p,li %p,sli %p,slii %p,buf %p\n",&gi,&gii,&si,&sii,&li,&sli,&slii,buf);
}
输出如下:
E:\SoftwareDevelopByMyself\Qt\Gvim>objdump -h a.exe
a.exe: file format pei-i386
Sections:
Idx Name Size VMA LMA File off Algn
0 .text 000007f4 00401000 00401000 00000400 2**4
CONTENTS, ALLOC, LOAD, READONLY, CODE, DATA
1 .data 00000044 00402000 00402000 00000c00 2**5
CONTENTS, ALLOC, LOAD, DATA
2 .rdata 00000328 00403000 00403000 00000e00 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
3 .buildid 00000035 00404000 00404000 00001200 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
4 .eh_frame 0000037c 00405000 00405000 00001400 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
5 .bss 00000104 00406000 00406000 00000000 2**5
ALLOC
6 .idata 00000294 00407000 00407000 00001800 2**2
CONTENTS, ALLOC, LOAD, DATA
7 .rsrc 000004e8 00408000 00408000 00001c00 2**2
CONTENTS, ALLOC, LOAD, DATA
8 .debug_aranges 00000178 00409000 00409000 00002200 2**0
CONTENTS, READONLY, DEBUGGING
9 .debug_info 00007c93 0040a000 0040a000 00002400 2**0
CONTENTS, READONLY, DEBUGGING
10 .debug_abbrev 00000c7c 00412000 00412000 0000a200 2**0
CONTENTS, READONLY, DEBUGGING
11 .debug_line 00000ed2 00413000 00413000 0000b000 2**0
CONTENTS, READONLY, DEBUGGING
12 .debug_str 00000136 00414000 00414000 0000c000 2**0
CONTENTS, READONLY, DEBUGGING
13 .debug_loc 000001a6 00415000 00415000 0000c200 2**0
CONTENTS, READONLY, DEBUGGING
14 .debug_ranges 00000018 00416000 00416000 0000c400 2**0
CONTENTS, READONLY, DEBUGGING
E:\SoftwareDevelopByMyself\Qt\Gvim>a.exe
gi 0x406018, gii 0x402008, si 0x40601c, sii 0x40200c,li 0x28cc58,sli 0x406020,slii 0x402010,buf 0x80075f20
可知:
bss段 0406000:未初始化的全局变量,未初始化的静态全局变量,未初始化的静态局部变量。
data段 0402000:初始化的全局变量,初始化的静态全局变量,初始化的静态局部变量。
局部变量 0x28cc5c,栈段。
堆区 0x80075f20。
上一篇: 天池o2o优惠券使用预测