Clang 中的结构填充警告

Xwi*_*arg 2 c padding

我创建了以下结构:

typedef struct  s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
}               t_fct_printf;

static const t_fct_printf       flags[] =
{
  { 's', my_putstr_printf },
  //[...]
  { 'b', display_base_2 },
};
Run Code Online (Sandbox Code Playgroud)

但是当我使用 clang option 编译时-Weverything,出现以下警告:

typedef struct  s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
}               t_fct_printf;

static const t_fct_printf       flags[] =
{
  { 's', my_putstr_printf },
  //[...]
  { 'b', display_base_2 },
};
Run Code Online (Sandbox Code Playgroud)

我找到了以下解决方案:

typedef struct  s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
  char          pad[7];
}               t_fct_printf;
Run Code Online (Sandbox Code Playgroud)

但这并不能解决问题:

warning: padding struct 'struct s_fct_printf' with 7 bytes to
      align 'fct' [-Wpadded]
Run Code Online (Sandbox Code Playgroud)

所以我尝试了:

typedef struct  s_fct_printf
{
  char          flag;
  char          pad[7];
  void          (*fct)(void*);
}               t_fct_printf;
Run Code Online (Sandbox Code Playgroud)

但出现以下错误:

typedef struct  s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
  char          pad[7];
}               t_fct_printf;
Run Code Online (Sandbox Code Playgroud)

我找到的最后一个解决方案是这样的,但我读到它没有优化,因为编译器不再打包我的变量。

typedef struct __atribute__((__packed__))       s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
}                                               t_fct_printf;
Run Code Online (Sandbox Code Playgroud)

有好的解决办法吗?

Pau*_*vie 6

我充分考虑了你的问题。我不认为添加填充字段是解决方案。它破坏了代码并引入了未来潜在的问题。

我还了解一个质量要求,即所有代码都应在编译时没有警告或错误。但是,此警告仅提供信息,并不表明可能存在错误。

我的建议是在警告发生的地方以及接受发生的地方明确抑制此警告。我建议(以VC为例):

#pragma warning(disable:4123)
// The compiler will inform that padding will insert 7 bytes after flag,
// which will be unused. This is acceptable.
typedef struct  s_fct_printf
{
  char          flag;
  void          (*fct)(void*);
}               t_fct_printf;
#pragma warning(enable:4123)
Run Code Online (Sandbox Code Playgroud)

我希望你的编译器有类似的机制。