gpt4 book ai didi

c - 为什么 gcc 允许类型为 void(非指针)的外部声明?

转载 作者:太空狗 更新时间:2023-10-29 16:27:09 25 4
gpt4 key购买 nike

为什么 gcc 允许 void 类型的外部声明?这是一个扩展还是标准C?这有可接受的用途吗?

我猜这是一个扩展,但我没有在以下位置找到它:
http://gcc.gnu.org/onlinedocs/gcc-4.3.6/gcc/C-Extensions.html

$ cat extern_void.c
extern void foo; /* ok in gcc 4.3, not ok in Visual Studio 2008 */
void* get_foo_ptr(void) { return &foo; }

$ gcc -c extern_void.c # no compile error

$ gcc --version | head -n 1
gcc (Debian 4.3.2-1.1) 4.3.2

将 foo 定义为 void 类型当然是一个编译错误:

$ gcc -c -Dextern= extern_void.c
extern_void.c:1: error: storage size of ‘foo’ isn’t known

为了比较,Visual Studio 2008 在 extern 声明上给出了一个错误:

$ cl /c extern_void.c 
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.

extern_void.c
extern_void.c(1) : error C2182: 'foo' : illegal use of type 'void'

最佳答案

奇怪的是(或者也许不是那么奇怪...)在我看来 gcc 接受这个是正确的。

如果这被声明为 static 而不是 extern,那么它将具有内部链接,并且 §6.9.2/3 将适用:

If the declaration of an identifier for an object is a tentative definition and has internal linkage, the declared type shall not be an incomplete type.

如果它没有指定任何存储类(extern,在这种情况下),那么 §6.7/7 将适用:

If an identifier for an object is declared with no linkage, the type for the object shall be complete by the end of its declarator, or by the end of its init-declarator if it has an initializer; in the case of function arguments (including in prototypes), it is the adjusted type (see 6.7.5.3) that is required to be complete.

无论是哪种情况,void 都不起作用,因为 (§6.2.5/19):

The void type [...] is an incomplete type that cannot be completed.

但是,

这些都不适用。这似乎只留下了 §6.7.2/2 的要求,它似乎允许声明类型为 void 的名称:

At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each struct declaration and type name. Each list of type specifiers shall be one of the following sets (delimited by commas, when there is more than one set on a line); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers.

  • void
  • char
  • signed char

[ ... more types elided]

我不确定这是否真的有意——我怀疑 void 确实是为派生类型(例如,指向 void 的指针)或函数的返回类型之类的东西而设计的,但我可以' 找到任何直接指定该限制的内容。

关于c - 为什么 gcc 允许类型为 void(非指针)的外部声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038964/

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