在我的x86_64 Linux机器上用GCC 4.5.3初始化结构时,我遇到了一个非常奇怪的问题。
有问题的代码:
struct apr_finfo_t info = { 0 };
apr_finfo_t是一个非常复杂的结构。我只想说它有17个复杂的其他成员。
struct apr_finfo_t {
/** Allocates memory and closes lingering handles in the specified pool */
apr_pool_t *pool;
/** The bitmask describing valid fields of this apr_finfo_t structure
* including all available 'wanted' fields and potentially more */
apr_int32_t valid;
/** The access permissions of the file. Mimics Unix access rights. */
apr_fileperms_t protection;
/** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE,
* APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE.
* If the type cannot be determined, the value is APR_UNKFILE.
*/
apr_filetype_e filetype;
/** The user id that owns the file */
apr_uid_t user;
/** The group id that owns the file */
apr_gid_t group;
/** The inode of the file. */
apr_ino_t inode;
/** The id of the device the file is on. */
apr_dev_t device;
/** The number of hard links to the file. */
apr_int32_t nlink;
/** The size of the file */
apr_off_t size;
/** The storage size consumed by the file */
apr_off_t csize;
/** The time the file was last accessed */
apr_time_t atime;
/** The time the file was last modified */
apr_time_t mtime;
/** The time the file was created, or the inode was last changed */
apr_time_t ctime;
/** The pathname of the file (possibly unrooted) */
const char *fname;
/** The file's name (no path) in filesystem case */
const char *name;
/** The file's handle, if accessed (can be submitted to apr_duphandle) */
struct apr_file_t *filehand;
};
现在,在使用GCC 4.5.3和 -std = c99 -pedantic -Wextra 编译此作品时,我看到以下警告信息:
src/switch_apr.c: In function ‘switch_file_exists’:
src/switch_apr.c:518: warning: missing initializer
src/switch_apr.c:518: warning: (near initialization for ‘info.valid’)
显然,GCC尝试初始化第一个成员,但已经在第二个成员上窒息。 如果不使用 -W / -Wextra 进行构建,则不会出现此警告。
我可以手动初始化每个成员,但这听起来很奇怪和错误。
从我从谷歌搜索中收集到的内容来看,这种初始化似乎是完全合法的,并且有关GCC 3的报告。但不是GCC 4.5或4.1。
希望有人可以提供帮助。 :)
致以最诚挚的问候,
米哈伊
答案 0 :(得分:3)
-Wextra
命令行选项包含-Wmissing-field-initializers
尝试将-Wno-missing-field-initializers
添加到命令行。
$ cat 7724939.c #include <stdlib.h> struct whatever { int a; int j; int k; }; int main(void) { struct whatever x = {0}; if (x.k) return EXIT_FAILURE; return 0; } $ gcc --version gcc (Debian 4.6.1-4) 4.6.1 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ gcc -std=c99 -pedantic 7724939.c $ gcc -std=c99 -pedantic -Wall -Wextra 7724939.c 7724939.c: In function ‘main’: 7724939.c:10:10: warning: missing initializer [-Wmissing-field-initializers] 7724939.c:10:10: warning: (near initialization for ‘x.j’) [-Wmissing-field-initializers] $ gcc -std=c99 -pedantic -Wall -Wextra -Wno-missing-field-initializers 7724939.c $
请注意,C标准不要求警告。这只是你的编译器试图(太)有用。
答案 1 :(得分:0)
如果你正在使用C ++,那么包含一个初始化的构造函数会好得多,这样初始化只需要在构造函数中而不是在任何地方编写。