Why does gcc allow extern declarations of type void (non-pointer)?

前端 未结 4 1410
广开言路
广开言路 2020-12-16 11:26

Why does gcc allow extern declarations of type void? Is this an extension or standard C? Are there acceptable uses for this?

I am guessing it is an extension, but

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 12:21

    One limitation of C's linker-interaction semantics is that it provides no mechanism for allowing numeric link-time constants. In some projects, it may be necessary for static initializers to include numeric values which are not available at compile time but will be available at link time. On some platforms, this may be accomplished by defining somewhere (e.g. in an assembly-language file) a label whose address, if cast to int, would yield the numeric value of interest. An extern definition can then be used within the C file to make the "address" of that thing available as a compile-time constant.

    This approach is very much platform-specific (as would be anything using assembly language), but it makes possible some constructs that would be problematic otherwise. A somewhat nasty aspect of it is that if the label is defined in C as a type like unsigned char[], that will convey the impression that the address may be dereferenced or have arithmetic performed upon it. If a compiler will accept void foo;, then (int)&foo will convert the linker-assigned address for foo to an integer using the same pointer-to-integer semantics as would be applicable with any other `void*.

    I don't think I've ever used void for that purpose (I've always used extern unsigned char[]) but would think void would be cleaner if something defined it as being a legitimate extension (nothing in the C standard requires that any ability exist anywhere to create a linker symbol which can be used as anything other than one specific non-void type; on platforms where no means would exist to create a linker identifier which a C program could define as extern void, there would be no need for compilers to allow such syntax).

提交回复
热议问题