F
funkyj
PROBLEM STATEMENT:
I want to calculate the byte offset of a field with a struct at
compile time without instantiating an instance of the struct at
runtime AND I want to do this in an ANSI standard compliant
fashion.
DISCUSSION:
Below is a sample program that demonstrates my solution. My questions
are:
(1) is this ANSI C compliant?
(2) is there a better way to solve this problem?
I think I'm on safe ground because casting and taking the address of
stuff does not cause memory to be accessed (i.e. pointers
dereferenced). In any event I seem to have satisfied GCC:
Regards,
--jfc
================ begin sample program offset.c ================
#include <stdio.h>
typedef struct {
long a, b, c;
short e, f;
char name[13];
long g, h;
char stuff[1 << 13];
short i;
char j;
long k, l, m;
char n, o, p;
} verybig_t;
#define MY_OFFSET(type, field) ((unsigned long ) &(((type *)
0)->field))
int main(int argc, char * argv[])
{
printf("MY_OFFSET(verybig_t, a) = 0x%x\n", MY_OFFSET(verybig_t,
a));
printf("MY_OFFSET(verybig_t, g) = 0x%x\n", MY_OFFSET(verybig_t,
g));
printf("MY_OFFSET(verybig_t, j) = 0x%x\n", MY_OFFSET(verybig_t,
j));
printf("MY_OFFSET(verybig_t, p) = 0x%x\n", MY_OFFSET(verybig_t,
p));
return(0);
}
I want to calculate the byte offset of a field with a struct at
compile time without instantiating an instance of the struct at
runtime AND I want to do this in an ANSI standard compliant
fashion.
DISCUSSION:
Below is a sample program that demonstrates my solution. My questions
are:
(1) is this ANSI C compliant?
(2) is there a better way to solve this problem?
I think I'm on safe ground because casting and taking the address of
stuff does not cause memory to be accessed (i.e. pointers
dereferenced). In any event I seem to have satisfied GCC:
> cd c:/cygwin/home/fj/offset/
> make offset && ./offset
> gcc -ansi -pedantic -o offset offset.c
> MY_OFFSET(verybig_t, a) = 0x0
> MY_OFFSET(verybig_t, g) = 0x20
> MY_OFFSET(verybig_t, j) = 0x202a
> MY_OFFSET(verybig_t, p) = 0x203a
>
> Compilation finished at Fri Feb 17 11:41:58
Regards,
--jfc
================ begin sample program offset.c ================
#include <stdio.h>
typedef struct {
long a, b, c;
short e, f;
char name[13];
long g, h;
char stuff[1 << 13];
short i;
char j;
long k, l, m;
char n, o, p;
} verybig_t;
#define MY_OFFSET(type, field) ((unsigned long ) &(((type *)
0)->field))
int main(int argc, char * argv[])
{
printf("MY_OFFSET(verybig_t, a) = 0x%x\n", MY_OFFSET(verybig_t,
a));
printf("MY_OFFSET(verybig_t, g) = 0x%x\n", MY_OFFSET(verybig_t,
g));
printf("MY_OFFSET(verybig_t, j) = 0x%x\n", MY_OFFSET(verybig_t,
j));
printf("MY_OFFSET(verybig_t, p) = 0x%x\n", MY_OFFSET(verybig_t,
p));
return(0);
}