I was using a header file in my project that had the following define(s):
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions*/
#else
#define __I volatile const /*!< Defines 'read only' permissions*/
#endif
The __I
is used as follows in another header file:
typedef struct {
// more members before
__I uint32_t CR; /*!< GPIO Commit*/
// more members after
} GPIOA_Type;
#define GPIOF_BASE 0x40025000UL
#define GPIOF ((GPIOA_Type *) GPIOF_BASE)
My question is why would the __I
be made const in C but not in C++? You can still modify the value CR is pointing to since you have the address, but am just curios why the definition of __I
is different.
For anybody interested what this is for or from,
the __I
defines are from IAR Embedded Workbench ARM for Cortex-M4
, and the struct is from Texas Instruments LM4F120H5QR CMSIS files.
Yes a C++ variable be both const and volatile. It is used in situations like a read-only hardware register, or an output of another thread. Volatile means it may be changed by something external to the current thread and Const means that you do not write to it (in that program that is using the const declaration).
Yes, it is possible. The best example is Status Register in controllers, in the program we should not modify this Status Register so it should be a constant.
Another use for a combination of const and volatile is where you have two or more processors communicating via a shared memory area and you're coding the side of this communications that will only be reading from a shared memory buffer.
Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in FAQ 8, the timer structure was accessed through a volatile const pointer.
In C++, const
variables at file scope default to static linkage, which wouldn't be desired for memory-mapped GPIOs. The "right" fix for that is the extern
keyword, but that can't be used here, since evidently __I
needs to work with class members as well. So eliminating const
makes the default linkage extern
, as desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With