i have a structure in my program and i want generate a compile error
when the size of structure is not pow of two.
my problem is that i don't found the way to get the size of structure
in preprocessor mode and it's necessary to generate a COMPILE ERROR
when the size of my struct is not pow of 2
The preprocessor cannot get the size of anything, not
even of a char, because the preprocessor operates at a time
before things like `char' have acquired any meaning: They're
just tokens ("preprocessing tokens," actually), and their
eventual effect of declaring types that have sizes is still
in the future.
However, you can cause compilation errors at a later
stage. One way is to declare an array type whose dimension
is invalid if the condition you're interested in doesn't hold:
char foo[ (sizeof(struct s) & (sizeof(struct s)-1)) == 0 ];
If the condition holds this is `char foo[1];' and valid; if the
condition doesn't hold it's `char foo[0];' which is invalid and
should generate a diagnostic. (Unfortunately, some compilers
fail to diagnose zero-dimension arrays; to get diagnostics even
from them you could use `char foo[... == 0 ? 1 : -1];' instead.)
The diagnostic will probably say something about the invalid
array dimension, rather than something helpful about the fact
that sizeof(struct s) isn't a power of two. One thing you can
do about that is use a comment:
/* If the compiler objects to the following declaration,
* the problem is that sizeof(struct s) should be a power
* of two but is not.
*/
char foo[...];
The person who investigates the funny-looking compiler complaint
will presumably arrive at the offending declaration of foo, and
will then see the comment that explains what's *really* wrong.
You don't have to use an array dimension as the thing the
compiler will object to. For example, you could declare a struct
having a bit-field whose width is given by the test expression
(note that `:0' *is* valid as a bit-field width, so make sure
the evaluation produces a negative number on failure).