【发布时间】:2012-04-19 19:18:44
【问题描述】:
为什么 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'
【问题讨论】:
-
有趣的是,即使使用
-std=c89 -pedanticgcc 也很酷。 -
据我了解,定义
void类型的变量格式不正确,但将extern应用于不完整类型并不是格式错误,对于example:extern在数组上大小未知,稍后定义。但是,§6.2.5.19 说 “void 类型包含一组空值;它是不完整的对象类型,无法完成。”,鉴于您的代码应被视为违反约束。它使用-pedantic干净地编译的事实表明它不是扩展,这是 gcc 错误或 msvc 和 gcc 解释标准的方式中的歧义。