gpt4 book ai didi

c++ - Visual Studio 2017 : ambiguous symbol size_t in linux projects

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:13 24 4
gpt4 key购买 nike

在 Visual Studio 2017 中创建 Linux 项目并在源代码中插入 using namespace std; 时,如下所示:

#include <iostream>
#include <string>

using namespace std;

int main()
{
size_t i = 1;
string s = to_string(i);
cout << i << s << endl;
return 0;
}

VS 下划线size_t 说是有歧义的符号。 VS pic 1

如果我按 F12(转到定义),它会为我提供两个定义位置:

来自 stddef.h

(C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Linux\include\usr\include\x86_64-linux-gnu\5\include\stddef.h):

// ...
namespace std
{
typedef __SIZE_TYPE__ size_t;
// ...

c++config.h

(C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Linux\include\usr\include\x86_64-linux-gnu\c++\5\bits\c++config.h):

// ...
#if !(defined (__GNUG__) && defined (size_t))
typedef __SIZE_TYPE__ size_t;
// ...

它只发生在 VS 中的 Linux 项目,而不是 Windows 项目。

是否有任何已知的解决方案(除了“不要使用 using namespace std; :) )?

Upd:向 Microsoft 报告此问题:https://developercommunity.visualstudio.com/content/problem/67405/ambiguous-symbol-size-t-in-linux-projects-when-usi.html

Upd2:Microsoft 表示已修复它,解决方案将在下一次更新中:https://developercommunity.visualstudio.com/content/problem/67405/ambiguous-symbol-size-t-in-linux-projects-when-usi.html

最佳答案

看起来 Microsoft 的编译器和其他编译器在命名空间内外的 typedef 方面存在差异。

这个源文件

namespace foo { typedef int moo; }
typedef int moo;
using namespace foo;
extern moo a;

在 g++ 和 clang++ 中编译(-Weverything 没有警告)。由于符号不明确,MSVC 拒绝了它。

这正是 gcc header 中 size_t 的情况。它在 namespace std 中和之外都是类型定义的。这似乎不会引起任何问题g++.

为什么在 g++ 中编译而不是在 msvc 中编译?我猜这是因为对 7.1.3/3 的不同解释

In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.

诚然,g++ 的解释相当松散。第一个 moo 未在 namespace:: 中声明,因此该规则似乎不适用。我找不到其他任何东西可以允许这样的事情。

为了解决这个问题,我会修补全局命名空间中定义了 size_t 的 header ,并将声明放在 namespace std 中(有条件的,如果 __cplusplus 已定义)。但我没有测试过它(这里没有 VC2017)并且不能保证它会起作用。

我也不知道为什么你的代码被实际的编译器接受而只被 IntelliSense 拒绝。我用实际的编译器测试了这个结构。 (更新 到最后一句话:我已经用 MSVC 测试了代码,但被 MSVC 拒绝了。我进行了测试,然后才意识到上面的“实际编译器”实际上是 gcc 而不是 MSVC) .

关于c++ - Visual Studio 2017 : ambiguous symbol size_t in linux projects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com