Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining struct member byte-offsets at compile-time?

I want to find the byte offset of a struct member at compile-time. For example:

struct vertex_t
{
    vec3_t position;
    vec3_t normal;
    vec2_t texcoord;
}

I would want to know that the byte offset to normal is (in this case it should be 12.)

I know that I could use offsetof, but that is a run-time function and I'd prefer not to use it.

Is what I'm trying to accomplish even possible?

EDIT: offsetof is compile-time, my bad!

like image 317
Colin Basnett Avatar asked Nov 13 '13 00:11

Colin Basnett


1 Answers

In C:

offsetof is usually actually a macro, and due to its definition, it will probably optimized by the compiler so that it reduces to a constant value. And even if it does become an expression, it is small enough that it should cause almost no overhead.

For example, at the file stddef.h, it is defined as:

#define offsetof(st, m) ((size_t)(&((st *)0)->m))

In C++:

Things get a bit more complicated, since it must resolve offsets for members as methods and other variables. So offsetof is defined as a macro to call another method:

#define offsetof(st, m) __builtin_offsetof(st, m)

If you need it only for structs, you are good enough with offsetof. Else, I don't think it is possible.

like image 146
Vinícius Gobbo A. de Oliveira Avatar answered Sep 21 '22 15:09

Vinícius Gobbo A. de Oliveira