Compilation error when offsetting structure member used as array length

When compiling the below code using GCC 4.8.3, I get the error "arrTest.c: 12: 4: error: variable sized object could not be initialized". But the same code compiles fine when compiled with GCC 4.1. Can anyone help me fix this?

#define OFFSET(structure, member)    /* byte offset of member in structure*/\
                ((const int) &(((structure *) 0) -> member))

typedef struct test{
   int a;
   char b;
   int c;
}test;

void main()
{
   int arr[OFFSET(test, b)] = {0};

   printf("%d %d\n", arr[0], OFFSET(test, b));

   return;
}

      

Removing the array initialization would fix the problem though. But there are many examples like this in my code. So I don't want to go anywhere and change. I wanted to know if there is any way in GCC 4.8 to fix this either with some compilation flags or by changing the definition of MACRO, since the same code is compiled with GCC 4.1.

+3


source to share


2 answers


Your macro is OFFSET

wrong in modern C as dereferencing a null pointer is undefined behavior; also, in modern C there is no provision for arbitrary pointer arithmetic to result in a compile-time constant, which is why gcc complains that the array is variable in size.

Fortunately, modern C provides a macro in that completely defines the behavior and results in a constant compile time offsetof

stddef.h

#include <stddef.h>
#define OFFSET(structure,member) offsetof(structure, member)

// rest of code

      



A living example .

I don't have access to old compilers like gcc 4.1, but if this is not supported offsetof

, you can revert to your definition by checking the conditional version of the preprocessor:

#ifdef __GNUC__ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC__MINOR__ >= 8))
#    include <stddef.h>
#    define OFFSET(structure,member) offsetof(structure, member)
#else
#    define OFFSET(structure, member)    /* byte offset of member in structure*/\
            ((const int) &(((structure *) 0) -> member))
#endif

      

+3


source


Try the C library offsetof()

. GCC uses a feature __builtin_offset()

and seems to work fine.



+2


source







All Articles