I defined uint16 variable. I want to have a validation in compilation that whenever this variable is used, it must be first transformed with hton(). Is there a way to validate it during gcc compilation?
Thanks.
I defined uint16 variable. I want to have a validation in compilation that whenever this variable is used, it must be first transformed with hton(). Is there a way to validate it during gcc compilation?
Thanks.
Not directly, no, I don't believe.
I believe the proper solution to this is ordinary abstraction. Set up a file that contains your variable, together with getter and setter routines:
/* var.c */
static uint16_t my_hidden_var;
void set_hidden_var (uint16_t v) {
my_hidden_var = v;
}
uint16_t get_hidden_var (void) {
return htons (my_hidden_var);
}
Obviously that's a simplistic example, and you'd probably want to add more, but the point is that your access requirements are enforced.
If that's too heavyweight, I'd create a macro as the getter (an inline function would work fine too):
#define GET_VAR() htons (var)
Then, any mention of "var" in your sources must be either incorrect, or an exception to the rule, and you can find them easily with a simple text search.
I don't think there is a proper solution to this in C, as there is no way we can verify that a variable has changed byte order by going through hton()
.
If somehow we are able to verify that, we could use a static assert (talked about here and here) and create compile time checks.
You could still write a macro after the declaration of your variable var
:
#define var hton(var)
This is probably a bad solution and could mess things up, so just use a function which returns the variable after running it through hton()
.