Determining the byte offset of a structure element at compile time?

I want to find the byte offset of the struct element at compile time. For instance:

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

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

I know that I could use offsetof , but this is a runtime function, and I would prefer not to use it.

Am I trying to make something even possible?

EDIT : offsetof - compilation time, my bad!

+6
source share
3 answers

offsetof is a compile-time constant if we look at the draft standard section of a C ++ C.3 C project, in paragraph 2:

The C ++ Standard Library provides 57 standard macros from the C library, as shown in Table 149.

and the table includes offsetof . If we move on to the standard section of Project C99 7.17 General Definitions, paragraph 3 includes:

offsetof (type, pointer member)

which expands to an integer constant expression of type size_t, a value that is an offset in bytes [...]

+7
source

In C:

offsetof usually a macro, and thanks to its definition, it is probably optimized by the compiler, so it comes down to a constant value. And even if it becomes an expression, it is small enough so that it does not cause almost any overhead.

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

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

In C ++:

Things get a little more complicated, as it needs to allow bias for members as methods and other variables. Thus, offsetof is defined as a macro to call another method:

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

If you only need this for structures, you are good enough with offsetof . Otherwise, I do not think it is possible.

+1
source

Are you sure it's runtime?

The following works ..

 #include <iostream> #include <algorithm> struct vertex_t { int32_t position; int32_t normal; int32_t texcoord; }; const int i = offsetof(vertex_t, normal); //compile time.. int main() { std::cout<<i; } 

Also see here offsetof at compile time

0
source

Source: https://habr.com/ru/post/957962/


All Articles