我创建了以下结构:
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 },
};
但是,当我使用clang -Weverything编译时,我有以下警告:
warning: padding struct 'struct s_fct_printf' with 7 bytes to
align 'fct' [-Wpadded]
我找到了以下解决方案:
typedef struct s_fct_printf
{
char flag;
void (*fct)(void*);
char pad[7];
} t_fct_printf;
但这并不能解决问题:
warning: missing field 'pad' initializer [-Wmissing-field-initializers]
{ 'b', display_base_2 },
warning: padding struct 'struct s_fct_printf' with 7 bytes to
align 'fct' [-Wpadded]
所以我试了一下
typedef struct s_fct_printf
{
char flag;
char pad[7];
void (*fct)(void*);
} t_fct_printf;
但是得到了以下错误:
warning: incompatible pointer to integer conversion initializing 'char'
with an expression of type 'void (void *)' [-Wint-conversion]
{ 'b', display_base_2 },
warning: suggest braces around initialization of subobject
[-Wmissing-braces]
{ 'b', display_base_2 },
warning: missing field 'fct' initializer [-Wmissing-field-initializers]
{ 'b', display_base_2 },
error: initializer element is not a compile-time constant
{ 's', my_putstr_printf },
我找到的最后一个解决方案是这样的,但是我读过它没有被优化,因为编译器不再打包我的变量了。
typedef struct __atribute__((__packed__)) s_fct_printf
{
char flag;
void (*fct)(void*);
} t_fct_printf;
有好的解决办法吗?
发布于 2016-11-17 22:20:31
我对你的问题给予了应有的考虑。我不认为增加一个填充字段是解决办法。它破坏了代码,并引入了潜在的未来问题。
我还理解一项质量要求,即所有代码都应该在编译时没有警告或错误。但是,此警告仅提供信息,并不指向可能的错误。
我的建议是在发生和发生的地方显式地禁止此警告。我建议(以“公约”为例):
#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)
我希望你的编译器有一个类似的机制。
https://stackoverflow.com/questions/40662265
复制相似问题