0

我定义了 uint16 变量。我想在编译中验证无论何时使用此变量,都必须首先使用 hton() 对其进行转换。有没有办法在 gcc 编译期间对其进行验证?

谢谢。

4

2 回答 2

1

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().

于 2013-07-10T12:35:53.587 回答
1

不直接,不,我不相信。

我相信对此的正确解决方案是普通的抽象。设置一个包含变量的文件,以及 getter 和 setter 例程:

/* 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);
}

显然,这是一个简单的示例,您可能还想添加更多内容,但关键是您的访问要求是强制执行的。


如果这太重了,我会创建一个宏作为 getter(内联函数也可以正常工作):

#define GET_VAR() htons (var)

然后,在您的来源中提到的“var”必须是不正确的,或者是规则的例外,您可以通过简单的文本搜索轻松找到它们。

于 2013-07-10T12:35:05.037 回答