为什么 C99 抱怨存储大小? [英] Why does C99 complain about storage sizes?

查看:15
本文介绍了为什么 C99 抱怨存储大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 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:

  1. net/if.h 包括 features.h
  2. 稍后,它在 #ifdef __USE_MISC 块内定义 struct ifreq.
  1. net/if.h includes features.h
  2. Later on, it defines struct ifreq inside a #ifdef __USE_MISC block.

所以:

  1. 什么是__USE_MISC?-- 这是 BSD 和 System V 共有的东西
  2. 此时是否已定义?-- 我们需要在 features.h
  3. 中检查
  1. What is __USE_MISC? -- it is stuff common to BSD and System V
  2. Is it defined at this point? -- We need to check that out in features.h

现在,features.h:

  1. 当您使用 --std=c99 时,GCC 默认定义 __STRICT_ANSI__(因为这就是 C99)
  2. 在预处理 features.h 时,当 __STRICT_ANSI__ 开启时,BSD 和 System V 功能不会启动.即 __USE_MISC 是未定义.
  1. When you use --std=c99 GCC by default defines __STRICT_ANSI__ (since thats what C99 is)
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆