Behind C++ [2]- Static Variables

本文通过修改简单的Hello World程序源代码,逐步展示了不同类型的静态变量如何被编译器放置到不同的内存区域中。具体探讨了普通静态变量和常量静态变量在数据段中的存储方式及其区别。

Well, let's change the previous helloworld program source code to following:

We newly added the SECOND line to declare a new static variable named s_Age, and set the initialized value with 0xAE; why to use the value of 0xAE? The most important reason is that it is the certain value and we can track it with this value in the following steps.

 

Ok, let's compile it with

$> g++ -o helloworld helloworld.cpp -save-temps

So, check the intermediate file "helloworld.ii", see what changed.

$> vim helloworld.ii

The new file contents what we concern are as following:

1136 # 2 "helloworld.cpp" 2
1137 static int s_Age = 0xAE;
1138 int main(int argc, char ** argv)
1139 {
1140  printf("Hello World/r/n");
1141  return 0;
1142 }

There are NO any changes for this change. Let's take a look at the Intermediate Assembly File. 

   

So, we can see the newly added static variable s_Age in the line 4 to line 5. It decorates the variable name with prefix "_", the new variable name for s_Age is "_s_Age" (in deed, it's a label for variable s_Age) , and it's value is the DEC value "174" of hex number "0xAE".

And look at the line 2 and line 3, these TWO lines declares the DATA secion, and the label _s_Age is just living in the DATA secion. Obviously, this DATA section can be accessed with READ and WRITE.

 

Well, make a conclusion, it is "STATIC variables are living in the DATA secion ". Is it really TRUE? Follow me, let's continue.

We will limited the variable s_Age with "const" keyword. Modify the source code for the declaration of variable s_Age with following code:

Compile the source code with option "-save-temps" and see the assembly file "helloworld.s". Now, it is contains following contents:

Can you see the last 5 line in the bottom? The const static variable s_Age is living in the READ-ONLY data section.

So, the Words Of Wisdom is:

  • The global static constant variables are placed in the READ-ONLY data section.
  • The global static non-constant variables are placed in the regular data secion.

Are above conclusions correct? Let's practice to take a check.

Modify the source code for the declaration of s_Age with following:

Compile the source code and check the assembly file, it should be as following:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值