Ark Khasin wrote, On 31/07/08 06:23:
I have a memory-mapped peripheral with a mapping like, say,
struct T {uint8_t read, write, status, forkicks;};
Be aware that the compiler is allowed to put in padding. Since this is
obviously for non-portable code it might be sufficient to just put in a
comment in the code stating that you are relying on the compiler not
putting in any padding.
If I slap a volatile on an object of type struct T, does it guarantee
that all accesses to the members are byte-wide, or is the compiler free
to read or read-modify-write in any data width it chooses?
The requirements on the compiler for volatile are quite lax and even
leave is up to the implementation to define what counts as accessing a
variable. So you should read your compiler documentation.
Imagine a processor which can physically only read/write in chunks of 64
bits but which nevertheless has a compiler with a "normal" 8 bit byte.
On such an implementation if the structure did not have any padding the
compiler would not be able to prevent all bytes being added.
Having said that, I would *expect* the compiler to "do the right
thing"(tm) in your case. I would expect this because by not doing so on
what I'm guessing is a compiler targeting a small embedded device would
make it hard to use.
Is slapping a volatile on each member of the struct definition any
different? better? worse?
It could be inconvenient. One thing I've sometimes wanted to do was use
a structure of that general type both for some in-normal-memory stuff
(without the volatile qualifier) and for the memory-mapped device.
volatile-qualifying the members would make this awkward.
There is also an argument that you should not use a struct for this
purpose *because* it could have padding, but if your code for
interfacing to the HW is nicely isolated and the compiler documentation
says it will work, then as it is highly system specific anyway I don't
see a real problem.
Sorry that the best advise is to read the compiler documentation, but it
really is your best chance to ensure it works correctly. The next best
advice would be asking in a group dedicated to your specific
implementation or in comp.arch.embed ded where there are a lot more
people who are regularly doing this kind of thing than there are in this
group.
Note your question *is* topical here since volatile *is* part of the
standard language, it's just that to achieve your aims you need to go
beyond the guarantees of the language to things guaranteed by your
specific implementation.
--
Flash Gordon