c++ - 与来自 time.h 的标识符 'clock' 发生冲突

标签 c++ g++ clang

下面的程序

#include <ctime>

struct clock {};

int main() {
    clock c;
}

无法在 g++ 5.4 和 clang 3.8(Ubuntu 64 位)上编译。

g++输出

clock.cpp: In function ‘int main()’:
clock.cpp:6:11: error: expected ‘;’ before ‘c’
    clock c;
          ^

clang 输出

clock.cpp:6:5: error: must use 'struct' tag to refer to type 'clock' in this scope
    clock c;
    ^
    struct 
/usr/include/time.h:189:16: note: struct 'clock' is hidden by a non-type declaration of 'clock' here
extern clock_t clock (void) __THROW;
               ^
1 error generated.

诊断的形式略有不同,但都与同一问题相关。与标准 C 函数存在冲突 clock以及程序中定义的同名结构。相关声明来自time.h :

extern clock_t clock (void) __THROW;

问题是:这些符号不应该在 std 中吗?命名空间,因为程序包括 <ctime> ?有趣的是,这个声明位于一个宏之后的几行,该宏显示为 __BEGIN_NAMESPACE_STD。 .此外,在 <ctime> , 可以看到:

namespace std
{
    using ::clock_t;
    using ::time_t;
    using ::tm;

    using ::clock;
    ...
}

这里有什么错误吗?

谢谢。

最佳答案

The question is: shouldn't such symbols be in the std namespace...

是的,他们是。不幸的是,C++ 标准还允许实现将来自 C 库派生头文件的名称放入全局命名空间。在这种情况下,您会得到 std::clock ::clock .

这适用于所有 <c*>具有相应 <*.h> 的 C++ header C 版本。

关于c++ - 与来自 time.h 的标识符 'clock' 发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39852545/

相关文章:

c++ - 从构建配置创建 Makefile

c++ - 有没有用 C++ 编写的流行的开源项目?

c++ - 使用 GCC 从 *nix 交叉编译到 Windows 是否允许使用 VC++ 尚不支持的功能?

python - 如何强制 pip 在 OSX 上使用 GCC?

c - 体系结构 x86_64 错误的 Makefile 重复符号?

c++ - 静态类成员获取 "undefined reference"。不知道为什么

c++ - 寻找与 _mm256_load_ps 类似的函数,但用于字符指针

c++ - 从 lambda (C++) 创建的 std::function 的奇怪返回行为

c++ - 在 dlopen 检测重复符号

c++ - Clang:类中定义的友元函数