Reputation: 15406
Let's say I have the following definitions :
/* Generic structure of entire SFR area for each UART module */
typedef struct tagUART {
unsigned int uxmode;
unsigned int uxsta;
unsigned int uxtxreg;
unsigned int uxrxreg;
unsigned int uxbrg;
} UART, *PUART;
/* SFR blocks for each UART module */
extern volatile UART UART1 __attribute__((__sfr__));
extern volatile UART UART2 __attribute__((__sfr__));
Now if I acces the register through UART1, everything is fine, but what if I us a pointer to the structure, how should I declare it to specify the whole aera pointed to is volatile ?
volatile UART * hw = &UART1;
Is that ok ?
Upvotes: 4
Views: 3212
Reputation: 22552
If you declare
extern volatile UART UART1;
Then any pointer derived from that variable will be of type volatile UART *
and as a matter of fact your compiler should issue a warning if you try to assign it to any other type of variable.
If you wish UART
to always be volatile
then you can typedef it as such
typedef volatile struct {...} tagUART UART;
Or as unwind said to declare specific fields as volatile
typedef struct tagUART {
volatile unsigned int uxmode;
unsigned int uxsta;
volatile unsigned int uxtxreg;
unsigned int uxrxreg;
unsigned int uxbrg;
} UART, *PUART;
The inline use of volatile
i.e.
while (*(volatile int *)&a) ;
is discouraged and should only be used for variables that are normally not volatile, but have to be in this context.
Another way is to have a union
where accessing one version is volatile another is not:
union {
volatile UART volatile_version;
UART normal;
};
Upvotes: 4
Reputation: 399989
I think that's the wrong way; what if somebody (=you three months later) uses a pointer to USART
but forget about the volatile
part?
The proper way is to declare each field as being volatile
. It's a bit messy, but better since it captures more of what you're trying to model right there in the code.
You often see a macro such as __IO
being used for fields of structures that model hardware registers, and it typically includes volatile
in its expansion.
Upvotes: 1