Pierre G.
Pierre G.

Reputation: 4431

address of member structure in map file?

There has been already question about this topic (notably How to get address of some struct member in array of structures).

My question is the following : when we use struct to describe a hardware device, so each structure member will correspond to some registers of the hardware device - how can we be sure that each member of the structure is mapped correctly on each register of the hardware ?

The ABI of the compiler dictates the alignment of the members, the user can also makes some mistake - and the only way to be sure that the mapping is done correctly is to check at run time. The map file (at least for GNU ld) does not provide any clue about the placement of structure members.

Would there be a way to know at compiler or link time where each structure members are located ?

Upvotes: 0

Views: 828

Answers (1)

Useless
Useless

Reputation: 67713

You can use offsetof along with, in C++, static_assert.

For example, the entirely arbitrary

#include <cstddef>
struct iom {     // off,len
  uint32_t rx;   // +0,4
  uint32_t tx;   // +4,4
  uint64_t clk;  // +8,8
  uint16_t irq;  // +16,2
};
static_assert(offsetof(iom,rx)==0);
static_assert(offsetof(iom,tx)==4);
static_assert(offsetof(iom,clk)==8);
static_assert(offsetof(iom,irq)==16);

If the static_assert fails, for example because your compiler aligns the members to 64-bit boundaries, you need a compiler specific way to alter the alignment and padding. Eg, with gcc,

    } __attribute__((packed));

at the end of the struct definition.


NB. I've answered for C++17.

C++11 or 14, or C11 require an error message as the second argument to static_assert, although you can wrap the whole thing in a macro to compose a nice string for you.

The offsetof macro works in C as well.

Upvotes: 3

Related Questions