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!
offsetof
is a compile time constant, if we look at the draft C++ standard sectionC.3
C standard library paragraph 2 says:and the table includes
offsetof
. If we go to the C99 draft standard section7.17
Common definitions paragraph 3 includes: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: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:If you need it only for structs, you are good enough with
offsetof
. Else, I don't think it is possible.Are you sure it is run-time?
The following works..
Also see here: offsetof at compile time