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.
asm ("incl %0" : "+rm"(count));
should work whethercount
is a local or global variable . The manual states Accessing data from C programs without using input/output operands (such as by using global symbols directly from the assembler template) may not work as expected.count
is being affected, so the optimizer is free to assume it never changes from the initial value of 0. From the docs: GCC does not parse the assembler instructions themselves and does not know what they mean or even whether they are valid assembler input.