--- In [email protected], "John Matthews" <jm5...@...> wrote:
> "Sharma, Hans Raj \(London\)" <hansraj_sharma@> wrote:
> > Can someone please help me understand how can I write a
> > program which, using volatile variable, access some memory
> > mapped devices?
>
> If you have an 8 bit register at address 0x1234 containing
> an unsigned 8 bit value, then you might do something like:
>
> volatile unsigned char *const reg = 0x1234;
Technically, this violates a constraint. Better (though not
commonly done) would be...
volatile unsigned char * const reg =
(volatile unsigned char *) 0x1234;
As you say elsethread...
#define REG ((volatile unsigned char *) 0x1234)
But more importantly, the mapping of an integer to a pointer
is implementation-defined. Some compilers may actually be
incapable of producing code that will dereference an absolute
memory address [e.g. most hosted implementations.]
You really do need to read the implementation documentation
to figure out what you need to do.
> printf("reg = %u\n", *reg);
Nit pick: There is no guarantee that unsigned char will
promote to unsigned int. The standard says that %u must
take an unsigned int argument, lest the behaviour be
undefined. [It also says that va_arg(unsigned) will work
for a non-negative int value, however it doesn't say that
printf uses va_arg.]
I haven't seen a system where this will seriously fail,
but I prefer...
printf("reg = %u\n", 0u + *reg);
> It might work without the volatile, but the volatile tells
> the compiler that the contents of the register might change
> outside of the thread's control eg. because another thread
> is modifying it. Thus it shouldn't do any optimizations
> which assume its value is constant between accesses.
Technically, what constitutes 'access' is implementation-
defined. You may well find that some compilers will ignore
volatile for ordinary declarations if it can deduce that
it is not relevant.
--
Peter