C keyword register 并讨论共同使用嵌入式汇编

C keyword register 并讨论共同使用嵌入式汇编



                          register 是C99 的keyword之中的一个.




register 是储存类型之中的一个.这里仅讨论register 储存类型。auto static extern的各种故事请移步《C on pointer》


                  A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

也就是说。你给一个变量加上register的储存类型修饰符,也仅仅是向编译器说明

               “嘿,哥们儿,这个变量我要常常訪问的,我想尽可能快的訪问这个变量”

               訪问一个变量最快的储存类型?寄存器类型


                接着编译器会依据实际情况来,看有没有剩余的经常使用寄存器来储存这个变量,有,太好了。把变量放到寄存器里面去。没有?那也没办法,寄存器用作数据交换。比較忙。你的register修饰符也没用


例如说 register int varible; 假设申请使用寄存器做储存类型失败,就会把varible 觉得int 类型。


GCC的实现策略:

                 The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1). Thus, the only operator that can be applied to an array declared with storage-class specifier register is sizeof.


                上面这段话指明了GCC的实现策略。就是简单的把register 声明简单的当做auto对待。一旦是寄存器变量,你就不能对其进行寻址了,仅仅能用sizeof。光说没用,測试才是硬道理.





咯,gcc 的报错就在这里(我把优化级别降到了最低-O,并且加入了printf打印语句就是操心gcc把程序非常多部分优化掉了.)


这里是register 申请成功的情况,可是这里的申请寄存器做储存类型有时候页会失败的(默认auto了)

依据@浪陨 的提示。假设使用嵌入式汇编就能强制的把变量的储存类型定做register。

这样的做法在 赵炯的《凝视》里面页有提到(page 48 第三章 3.3.2)

“  假设想指定寄存器(比如 eax)那么我们能够把该语句写成 register char __res asm("ax");   ”

到了汇编层面。do what you want。坏笑....

这样的定义方式确实比較“霸道”,占用了寄存器,在其生命周期内不同意别的变量使用该寄存器. 寄存器是非常宝贵的~


如有误解。往批评指正.



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/hrhguanli/p/4726956.html