【问题标题】:Compiler doesn't see the C++11 identifiers编译器看不到 C++11 标识符
【发布时间】:2022-01-27 20:56:19
【问题描述】:

当我尝试构建 Google 测试 c++ 项目时,我发现了错误

Error   C3861   't1': identifier not found
Error   C2065   't1': undeclared identifier
Error   C2039   'thread': is not a member of 'std'
Error   C2065   'thread': undeclared identifier
Error   C2146   syntax error: missing ';' before identifier 't1'

我的测试代码是:

#include <future>
#include <thread>

#include "pch.h"
TEST(...)
{
    // preconditions here

    std::thread t1([&] {
        Sleep(100);
        testee.enqueue(item);
        });
    
    t1.join();
    
    // other logic
}

为什么我不能在我的项目中使用 std::thread 和其他 C++11 功能?我该怎么做?

【问题讨论】:

  • #include &lt;thread&gt;了吗?哪个版本的视觉工作室?哪些编译器标志?
  • @mch 是的,我做了#include &lt;thread&gt;。我使用 Visual Studio 2017。在哪里可以看到 VS 2017 中的编译器标志?
  • @AlanBirtles,希望我按照你的意愿编辑
  • Visual Studio 2017 支持 C++14(默认)或 C++17 标准。它不支持旧标准,所以&lt;thread&gt; 肯定是众所周知的。正如@273K 回答的那样,问题是由预编译的标头引起的。

标签: c++ visual-studio c++11 googletest


【解决方案1】:

#include "pch.h" 必须是第一个。 #include "pch.h" 之前的其他 #include 指令将被忽略。

【讨论】:

  • 确实如此。 #include "pch.h" 之前的 Everything 会被 MSVC 编译器忽略(使用 /Yu"pch.h" 编译器选项)。这包括#include#define、类声明,甚至像随机文本这样的语法错误!我被抓了几次,所以我现在用一个 Git 钩子强制执行每个 .cpp#include "pch.h" 开头。
  • 不错的评论!我从来没有遇到过这样的麻烦,因为我从来没有在#include 之前添加过代码。欢迎您修改我的答案或添加您自己的答案。
【解决方案2】:

为什么我不能在我的项目中使用 std::thread 和其他 C++11 功能?

潜在原因 1:除非使用 C++11 或更高版本的标准,否则无法使用 C++11 功能。

潜在原因 2:除非包含定义 std::thread 的标头,否则不能使用 std::thread。它在标题 &lt;thread&gt; 中定义。

【讨论】:

  • 如何确保我使用的是 C++11 或更高版本的标准?
  • @FooBoy 取决于您使用的编译器。查阅编译器的手册。
【解决方案3】:

关于pch.h,可以参考这个issue。我在VS2019中测试了你上传的代码,代码没有错误。结果如图所示。

#include <iostream>
#include <future>
#include <thread>
#include<Windows.h>
int main()
{
    std::thread t1([&] {
        Sleep(1000);
        });

    t1.join();
} 

关于C++11的使用,可以在项目属性>配置属性>通用>C++语言标准中进行设置。我建议你使用 C++14,因为 C++14 已经包含了 C++11 的特性。

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多