- 论坛徽章:
- 0
|
写一段代码来试验下:
volatile.c
- #include <stdio.h>
- int volatile mytest = 1;
- int main ()
- {
- mytest= 3;
- mytest = 4;
- printf("mytest = %d\n", mytest);
- return 0;
- }
复制代码 non_volatile.c
- #include <stdio.h>
- int mytest = 1;
- int main ()
- {
- mytest= 3;
- mytest = 4;
- printf("mytest = %d\n", mytest);
- return 0;
- }
复制代码 编译:
gcc -O2 -o volatile volatile.c
objdump -D volatile > volatile_dump
gcc -O2 -o non_volatile non_volatile.c
objdump -D non_volatile > nonvolatile_dump
objdump之:
volatile_dump
- 08048328 <main>:
- 8048328: 55 push %ebp
- 8048329: 89 e5 mov %esp,%ebp
- 804832b: 83 ec 08 sub $0x8,%esp
- 804832e: 83 e4 f0 and $0xfffffff0,%esp
- 8048331: c7 05 28 94 04 08 03 movl $0x3,0x8049428
- 8048338: 00 00 00
- 804833b: c7 05 28 94 04 08 04 movl $0x4,0x8049428
- 8048342: 00 00 00
- 8048345: 83 ec 08 sub $0x8,%esp
- 8048348: a1 28 94 04 08 mov 0x8049428,%eax
- 804834d: 50 push %eax
- 804834e: 68 08 84 04 08 push $0x8048408
- 8048353: e8 10 ff ff ff call 8048268 <_init+0x38>
- 8048358: 31 c0 xor %eax,%eax
- 804835a: c9 leave
- 804835b: c3 ret
复制代码 non_volatile_dump
- 08048328 <main>:
- 8048328: 55 push %ebp
- 8048329: 89 e5 mov %esp,%ebp
- 804832b: 83 ec 08 sub $0x8,%esp
- 804832e: 83 e4 f0 and $0xfffffff0,%esp
- 8048331: 83 ec 08 sub $0x8,%esp
- 8048334: 6a 04 push $0x4
- 8048336: 68 fc 83 04 08 push $0x80483fc
- 804833b: c7 05 1c 94 04 08 04 movl $0x4,0x804941c
- 8048342: 00 00 00
- 8048345: e8 1e ff ff ff call 8048268 <_init+0x38>
- 804834a: 31 c0 xor %eax,%eax
- 804834c: c9 leave
- 804834d: c3 ret
- 804834e: 90 nop
- 804834f: 90 nop
复制代码 很明显,volatile.c里的两次变量赋值未被优化掉,non_volatile.c里的两次变量赋值被优化成一次。
所以volatile关键字是起到了对编译器指示的作用,指示编译器不要对volatile的变量做优化。 |
|