gpt4 book ai didi

c - 当结构初始化与结构类型定义不匹配时,如何让 GCC 给出错误消息?

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:22 28 4
gpt4 key购买 nike

我有一个问题,当结构的初始化与其结构类型定义不匹配时,gcc 不会生成错误——即使编译器可能以最挑剔的模式运行。

以下命令由 ma​​ke 在一个包中调用,该包是在我所谓的“开发人员模式”下配置的——这是添加了一个选项,这样编译器就会变得挑剔并且尽可能地娇气 - 从而让开发人员知道代码中有一些需要修复的地方。

gcc -Wall -Qunused-arguments -Werror -I./libchbclib/inc -I/Users/red_angel/chorebox_sys/include -c -o tmp/lchbclib/chbclib_strq_new.o ./libchbclib/csrc/chbclib_strq_new.c

它(目前)进行了所有编译和构建,没有错误,包括以下 block 引用....

static chbclib_strq_cl st_mainclass =
{
st_meth_add // m_add
};

...在包中其他位置的包含文件中引用以下结构....

typedef struct chbclib_strq_cl {
bool (*m_add) ( void *srf_aa, char *rg_a );
// Adds a new string to the queue. Failure to do so is a
// fatal-error to the program if the objects 'erat' value
// is 0. Other wise, the boolean return value will let
// the calling program know whether or not the operation
// was a success.
} chbclib_strq_cl;

当然,到目前为止,构建没有错误是可以的。但是,当我对包含文件进行以下更改时,它应该生成错误 ----

typedef struct chbclib_strq_cl {
bool (*m_add) ( void *srf_aa, char *rg_a );
// Adds a new string to the queue. Failure to do so is a
// fatal-error to the program if the objects 'erat' value
// is 0. Other wise, the boolean return value will let
// the calling program know whether or not the operation
// was a success.

bool (*m_axd) ( void *srf_aa, char *rg_a );
// Adding this to the structure-type definition should produce
// an error ---- but it doesn't.

} chbclib_strq_cl;

--- 但出于某种原因,它仍然不会产生错误。

如果结构的初始化与结构类型定义不匹配,有什么方法可以强制 gcc 编译器生成错误?谢谢。

当然 --- 你们中的一些人可能想知道为什么我提示错误消息存在。答案是这样的——当我在非开发人员模式下构建包时,我可以接受错误不存在。但是,我专门实现了开发人员模式选项,因为我希望尽可能多地提醒我代码中的任何问题。

在这种情况下,示例是如果我有一个结构类型,该结构类型在程序的不同部分初始化了多个该类型的结构,并且我向该结构类型添加了一个字段(或进行任何其他更改) ,我还需要在程序中初始化该类型结构的每个其他地方更新代码。但是,如果我在该更新中“错过了一个地方”怎么办?如果发生这种情况,我指望一条错误消息来提醒我。

那么 --- 当我在开发者模式下配置包时,如何让 gcc 满足这一重要需求?

最佳答案

您可能正在寻找 -Wmissing-field-initializers 选项。

使用 -Wextra 时默认启用。

来自 gcc 版本 4.8.2 联机帮助页:

   -Wmissing-field-initializers
Warn if a structure's initializer has some fields missing. For example, the following code causes such a warning, because "x.h" is implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so the following modification
does not trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
This warning is included in -Wextra. To get other -Wextra warnings without this one,
use -Wextra -Wno-missing-field-initializers.

使用此选项时,Clang 将比 GCC 更频繁地触发警告。如果 GCC 没有发出警告,请尝试使用 Clang 看看是否有变化。

对于 gcc 版本 4.8.2,在某些情况下不会触发警告(例如,当只有第一个字段初始化为零时),但还要注意,这取决于您使用什么标准来编译您的代码,第一个结构字段之前的未初始化结构字段可能被接受为有效 C。

关于c - 当结构初始化与结构类型定义不匹配时,如何让 GCC 给出错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952053/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com