简体   繁体   English

外部函数指针声明和类型推断定义

[英]Extern function pointer declaration and type inferred definition

I recently received a code that is accepted by clang++ but not by g++ and I would like to know which one is right. 我最近收到的代码被clang ++接受但不是g ++,我想知道哪一个是正确的。

The minimalist code reproducing the behavior is very short and talk by itself so I think an explanation would be unnecessarily complicated. 再现行为的极简主义代码非常短并且单独说话,所以我认为解释会不必要地复杂化。

Here is a header containing an extern pointer declaration : 这是一个包含extern指针声明的标头:

//(guards removed for simplicity) :
#include <type_traits>

using ptr_func = std::add_pointer<void()>::type;

extern ptr_func pointer;

And here is the source implementing the needed pointed function : 以下是实现所需指向函数的源代码:

#include "function.hh"

void foo() {}

auto pointer = &foo;

The error generated by gcc is as follows : gcc生成的错误如下:

g++ -c function.cc -std=c++14
function.cc:5:6: error: conflicting declaration ‘auto pointer’
 auto pointer = &foo;
      ^
In file included from function.cc:1:0:
function.hh:5:17: note: previous declaration as ‘void (* pointer)()’
 extern ptr_func pointer;
                 ^

Clang accepts this code without any error/warning. Clang接受此代码时没有任何错误/警告。 And replacing the pointer definition by : 并通过以下方式替换指针定义:

decltype(foo)* pointer = &foo;

is accepted by gcc. 被gcc接受。

In my opinion, clang is right, but I am not sure so I would like to know if clang is too permissive or if gcc should accept it. 在我看来,clang是对的,但我不确定所以我想知道clang是否过于宽松或者gcc是否应该接受它。

This is definitely a bug in gcc. 这肯定是gcc中的一个bug。 Here's a minimal example: 这是一个最小的例子:

int foo;
extern int* ptr;
auto ptr = &foo;

Interestingly, gcc is happy if the extern and auto declarations are reversed. 有趣的是,如果externauto声明被颠倒,gcc很高兴。

This seems to be the same as https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60352 , reported last year. 这似乎与去年报道的https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60352相同。

The relevant clause is [basic.link] /10: 相关条款是[basic.link] / 10:

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). 在对类型进行所有调整之后(其中typedefs(7.1.3)被其定义替换),引用给定变量或函数的所有声明指定的类型应该是相同的,除了数组对象的声明可以指定数组类型是否存在主阵列界限(8.3.4)。 A violation of this rule on type identity does not require a diagnostic. 违反此规则的类型标识不需要诊断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM