gcc 内联汇编中 volatile 的含义

这个问题其实网上很多说明了,只是有一次公司学习上,一个大牛说 volatile 的意思是告
诉编译器我的内联汇编代码中对寄存器进行了修改,而另一个说意思是 volatile 告诉编译
器不要对这段汇编代码进行优化,因此产生了一些迷惑。

先看一下 gnu 的官方文档里怎么说的:

GCC’s optimizers sometimes discard asm statements if they determine there is
no need for the output variables. Also, the optimizers may move code out of
loops if they believe that the code will always return the same result (i.e.
none of its input values change between calls). Using the volatile qualifier
disables these optimizations. asm statements that have no output operands,
including asm goto statements, are implicitly volatile.

参考文档是这个
尝试翻译一下:

如果 GCC 的优化器发现输出变量没有必要,就有可能会丢弃 asm 语句。此外,如果优化
器认为代码总是返回相同的结果(即,在多次调用之间输入值不会改变),它可能会将代
码移动到循环外面。使用 volatile 关键字会禁止这些优化。如果 asm 语句没有输出部
分,包括 asm goto 语句,都隐含使用 volatile 关键字。

其中 “including asm goto statements” 我不太理解,难道是在内联汇编里进行 goto 跳
转?但无论如何,volatile 的意思已经很清楚了,就是防止编译器优化我们的汇编代码。
不过我也没有看完整个文档,所以也可能有其他一些细节没注意到,如果有请指正。

0%