【问题标题】:Clang compilation error on MacOS [closed]MacOS上的Clang编译错误[关闭]
【发布时间】:2018-05-12 12:34:20
【问题描述】:

这个问题似乎只出现在 MacOS 上,在 linux 上也可以使用 clang 编译。

以下代码是一个简化,但演示了问题,

#include<iostream>
int index = 0;
int main()
{
    std::cout << index << std::endl;
}

在编译时抛出此错误:

    main.cpp:2:5: error: redefinition of 'index' as different kind of symbol
int index = 0;
    ^
/usr/include/strings.h:73:7: note: previous definition is here
char    *index(const char *, int) __POSIX_C_DEPRECATED(200112L);
         ^
main.cpp:5:18: warning: address of function 'index' will always evaluate to
      'true' [-Wpointer-bool-conversion]
    std::cout << index << std::endl;
              ~~ ^~~~~
main.cpp:5:18: note: prefix with the address-of operator to silence this warning
    std::cout << index << std::endl;
                 ^
                 &
1 warning and 1 error generated.

这些是使用的编译器参数:

clang++ -std=c++11 main.cpp -o test

当使用 stdio 删除 iostream 时,代码按预期编译。他们是解决这个问题的方法还是我必须重命名我的变量以避免这种情况?

我确实找到了this,但我已经在使用 C++11 标志,而且 -std=c11 标志似乎对 C++ 代码无效。

【问题讨论】:

  • 你为什么期望它编译?
  • 你认为index是什么?
  • 不小心弄错了索引应该是名称而不是类型。
  • 您显然是在重新输入代码 - 不要那样做 - 使用复制和粘贴来发布它。
  • 代码和错误信息不匹配。请从示例代码中发布真正的错误。

标签: c++ macos clang++


【解决方案1】:

当您包含&lt;iostream&gt; 时,您使用的特定版本的clang/xcode 恰好包含&lt;strings.h&gt; 标头。 &lt;strings.h&gt; 在全局范围内提供了一个名为 index() 的函数。因此,您不能在全局范围内也声明具有相同名称的变量。

要么重命名变量,要么将其移动到main()

#include <iostream>

int main()
{
    int index = 0;
    std::cout << index << std::endl;
}

之所以有效,是因为当一个变量与其他变量具有相同的标识符但在不同的范围内时,它会被视为完全不同的实体。

举个例子说明它是如何工作的,请考虑以下代码:

#include <iostream>

int myVar = 0;

int main()
{
    int myVar = 1;
    std::cout << myVar << '\n';
    std::cout << ::myVar << '\n';
}

这将打印:

1
0

因为myVar 指的是局部变量,而::myVar 指的是全局范围内的变量。

【讨论】:

  • 他们的版本或 Xcode/clang 是否不包含 strings.h?从搜索结果中我发现它似乎是 Mac 中的默认标题。我目前使用的是 Apple LLVM 版本 9.0.0 (clang-900.0.38)
  • @ErikW 不知道。无论如何,这不是你可以控制的。因此,要么使用不同的名称,将变量移动到另一个范围,要么使用 Caleb 在另一个答案中指出的命名空间。
【解决方案2】:

他们是解决这个问题的方法还是我必须重命名我的变量以避免这种情况?

C++ 专门提供命名空间以避免名称之间的冲突。您可以为您的变量创建一个:

#include<iostream>

namespace MyGlobals {
    int index = 0;
}

int main()
{
    std::cout << MyGlobals::index << std::endl;
}

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 2014-05-18
    • 2019-03-08
    • 2016-04-04
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多