为什么 C99 抱怨存储大小? [英] Why does C99 complain about storage sizes?
问题描述
这是我在 Linux 上编译的一些代码:
This is some code I'm compiling on Linux:
#include <net/if.h>
int main() {
struct ifreq ifr;
}
gcc test.c
没问题.
gcc -std=gnu99 test.c
没问题.
gcc -std=c99 test.c
失败并出现以下错误:
gcc -std=c99 test.c
fails with the following error:
test.c: In function ‘main’:
test.c:4:16: error: storage size of ‘ifr’ isn’t known
C99不喜欢Linux中struct ifreq
的定义有什么不同?
What's different about C99 that it doesn't like the definition of struct ifreq
in Linux?
推荐答案
这是预处理和 GNU C 与 C99 的一系列后果.
It's a chain of consequences of preprocessing and GNU C vs C99.
首先,net/if.h
:
net/if.h
包括features.h
- 稍后,它在
#ifdef __USE_MISC
块内定义struct ifreq
.
net/if.h
includesfeatures.h
- Later on, it defines
struct ifreq
inside a#ifdef __USE_MISC
block.
所以:
- 什么是
__USE_MISC
?-- 这是 BSD 和 System V 共有的东西 - 此时是否已定义?-- 我们需要在
features.h
中检查
- What is
__USE_MISC
? -- it is stuff common to BSD and System V - Is it defined at this point? -- We need to check that out in
features.h
现在,features.h
:
- 当您使用
--std=c99
时,GCC 默认定义__STRICT_ANSI__
(因为这就是 C99) - 在预处理
features.h
时,当__STRICT_ANSI__
开启时,BSD 和 System V 功能不会启动.即__USE_MISC
是未定义.
- When you use
--std=c99
GCC by default defines__STRICT_ANSI__
(since thats what C99 is) - While preprocessing
features.h
, when__STRICT_ANSI__
is on, the BSD and System V features don't kick in. i.e.__USE_MISC
is left undefined.
备份到net/if.h
:预处理后struct ifreq
甚至都不存在了!因此,关于存储大小的投诉.
Back up to net/if.h
: struct ifreq
does not even exist after preprocessing! Therefore, the complaint about storage size.
您可以通过以下方式了解整个故事:
You can catch the whole story by doing:
vimdiff <(cpp test.c --std=c99 -dD) <(cpp test.c --std=gnu99 -dD)
或以任何其他方式区分它们(如 diff --side-by-side
)而不是 vimdiff
.
or diff'ing them in any other way (like diff --side-by-side
) instead of vimdiff
.
如果您希望使用 -std=c99
进行干净编译,则必须考虑包含 _DEFAULT_SOURCE
功能测试宏(对于 glibc 版本 >= 2.19;对于较旧的 glibc 版本,请使用 _BSD_SOURCE
或 _SVID_SOURCE
),以便在 C99 提供的功能之上启用所需的功能.
If you want this to cleanly compile with -std=c99
, you must consider the inclusion of the _DEFAULT_SOURCE
feature test macro (for glibc versions >= 2.19; for older glibc versions, use either _BSD_SOURCE
or _SVID_SOURCE
) so that the required functionality is enabled on top of what is offered by C99.
这篇关于为什么 C99 抱怨存储大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!