Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if gcc agrees that something is volatile?

Consider the following:

volatile uint32_t i;

How do I know if gcc did or did not treat i as volatile? It would be declared as such because no nearby code is going to modify it, and modification of it is likely due to some interrupt.

I am not the world's worst assembly programmer, but I play one on TV. Can someone help me to understand how it would differ?

If you take the following stupid code:

#include <stdio.h>
#include <inttypes.h>

volatile uint32_t i;

int main(void)
{
        if (i == 64738)
                return 0;
        else
                return 1;
}

Compile it to object format and disassemble it via objdump, then do the same after removing 'volatile', there is no difference (according to diff). Is the volatile declaration just too close to where its checked or modified or should I just always use some atomic type when declaring something volatile? Do some optimization flags influence this?

Note, my stupid sample does not fully match my question, I realize this. I'm only trying to find out if gcc did or did not treat the variable as volatile, so I'm studying small dumps to try to find the difference.

like image 731
Tim Post Avatar asked Mar 13 '09 12:03

Tim Post


People also ask

How do you declare volatile?

To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition.

When variables should not be declared as volatile?

Note, however, that if the DDI data access functions are used to access device registers, it is not necessary to use volatile. When data refers to global memory that is accessible by more than one thread, that is not protected by locks, and that relies on the sequencing of memory accesses.

What is a volatile statement?

Statement and Attribute: Specifies that the value of an object is entirely unpredictable, based on information local to the current program unit. It prevents objects from being optimized during compilation.

Is volatile global variable C?

No, globals are not implicitly volatile. Your assumption that threads could communicate only through the use of global variables is incorrect. All variables, not only globals, can be shared between threads --- for example, by passing their addresses to thread functions.


1 Answers

Many compilers in some situations don't treat volatile the way they should. See this paper if you deal much with volatiles to avoid nasty surprises: Volatiles are Miscompiled, and What to Do about It. It also contains the pretty good description of the volatile backed with the quotations from the standard.

To be 100% sure, and for such a simple example check out the assembly output.

like image 73
Anonymous Avatar answered Oct 24 '22 01:10

Anonymous