简体   繁体   English

示例C代码演示了反汇编中的volatile?

[英]Example C code that demonstrates volatile in disassembly?

What is a short illustrative C program that demonstrates the difference between volatile and non-volatile in the disassembly? 什么是简短的说明性C程序,它演示了反汇编中易失性和非易失性之间的区别?

ie

int main()
{
    volatile int x;

    ???
}

vs VS

int main()
{
    int x;

    ???
}

What can we replace both ??? 什么可以取代两个??? with such that the generated code is different? 这样生成的代码是不同的?

for example: 例如:

x = 0;

If x is not volatile , the compiler will see that it's unused and will probably eliminate it (either the x = 0; statement or even the variable itself) completely from the generated code as an optimization. 如果x不是volatile ,编译器将看到它未被使用,并且可能完全从生成的代码中作为优化消除它( x = 0;语句甚至变量本身)。

However, the volatile keyword is exactly for preventing the compiler from doing this. 但是, volatile关键字正是为了防止编译器执行此操作。 It basically tells the code generator "whatever you think this variable is/does, don't second guess me, I need it." 它基本上告诉代码生成器“无论你认为这个变量是什么/做什么,不要再猜测我,我需要它。” So then the compiler will treat the volatile variable as accessed and it will emit the actual code corresponding to the expression. 因此,编译器会将volatile变量视为已访问,并将发出与表达式对应的实际代码。

This may not be the shortest example, but it's a common use of volatile in embedded systems , assuming x points to the address of a register, if volatile is not used, the compiler will assume the value of x doesn't change and will remove the loop: 这可能不是最短的例子,但它是嵌入式系统volatile的常见用法,假设x指向寄存器的地址,如果不使用volatile ,编译器将假设x的值不会改变并将删除循环:

volatile long *x = (long*) REGISTER_BASE;
while (!(x&0x01)) {
   //do nothing;
}

You can also try this: 你也可以试试这个:

x=1;
x=2;
return x;

Turn on optimization an check the disassembly for both. 打开优化,检查两者的反汇编。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM