Question

I'm using a lot of volatile variables in my embedded firmware, but most of the time there is only one point in a function where I need to be sure the value is recent (at the start). But the rest of the function is referring to the same variable-name, and the value can be changed in the mean time, producing very unexpected code flow / results. I know this can be solved by using a temporary variable inside the function, but I was looking for a better solution.

Now I was wondering, instead of marking the whole variable as volatile, is there a way I could instruct the compiler (gcc) with a special keyword that I want to read the variable as if it was marked volatile, so I can use that keyword only once at the beginning of the function?

Was it helpful?

Solution

I'm a little confused about the scenario - if it's that you want one particular access to a variable to be treated as volatile, use

dest = *(volatile TYPE *)&src;

where TYPE is the type of src. You may also need

asm volatile ("" ::: "memory");

in carefully controlled locations, to prevent the compiler from moving loads/stores of other memory locations across the volatile read.

Also investigate C11's _Atomic types. (I'm not sure if GCC supports these yet.)

OTHER TIPS

If your variable is in memory and your embedded system supports it you could use memory barriers. To make sure that nothing accesses the memory while you are reading the value out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top