简体   繁体   中英

how to declare pointer to volatile struct

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 ?

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 ie

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;
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM