Search code examples
gccassemblyoptimizationinlinevolatile

volatile keyword does not work for gcc inline assembly


I need to run this simple inline assembly code:

#include <stdio.h>

int count;

int main() {

  count = 0;
  for (int i = 0; i < 10; i++) {
    asm volatile ("incl count");  // count++
  }

  printf("count=%d\n", count); 

  return 0;
}

It works fine (printing count=10) until I turn on optimization (gcc -O1), in which case it prints count=0. I read that the "volatile" qualifier will prevent the optimizer to put the code out of loop. But it seems to have no effect here.


Solution

  • Problem found. I had to define the global variable "count" as volatile. The problem was not putting asm block out of the loop. The compiler simply replaced count with 0 in printf.

    volatile int count;
    
    int main() {
    
      count = 0;
      for (int i = 0; i < 10; i++) {
        asm volatile ("incl count");  // count++
      }
    
      printf("count=%d\n", count); 
    
      return 0;
    }