为什么要设置参数

最近在学习C++,在学习多线程的时候,发现使用C++11中的thread类写的代码编译会报错:

 *正在执行任务: g++ -Wall -Wextra -g3 /Users/anweiyang/studySrc/C++/ThreadTest.cpp -o /Users/anweiyang/studySrc/C++/output/ThreadTest /Users/anweiyang/studySrc/C++/ThreadTest.cpp:21:12: error: no matching constructor for initialization of 'std::thread'thread t1(func, val1, val2); ^~~~~~~~~~~~~~~~~/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/thread:224:5: note: candidate constructor not viable: requires 1 argument, but 3 were providedthread(const thread&);^/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/thread:343:9: note: candidate constructor template not viable: requires single argument '__f', but 3 arguments were providedthread::thread(_Fp __f)^/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/thread:249:5: note: candidate constructor not viable: requires single argument '__t', but 3 arguments were providedthread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {^/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/thread:231:5: note: candidate constructor not viable: requires 0 arguments, but 3 were providedthread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}^1 error generated. *终端进程“g++ '-Wall', '-Wextra', '-g3', '/Users/anweiyang/studySrc/C++/ThreadTest.cpp', '-o', '/Users/anweiyang/studySrc/C++/output/ThreadTest'”已终止,退出代码: 1。*终端将被任务重用,按任意键关闭。 

查了一下报错的原因,最终发现是因为使用了 C++11 标准的 thread类,但是编译的时候并没有指定使用 C++11 标准,需要在编译时使用 -std=c++11 标志将编译器设置为使用 C++11 标准或更高版本的特性和语法。这样可以确保编译器能够正确解析线程构造函数的重载。
那么问题来了,执行程序的时候,我都是直接点击运行按钮的,如何配置这个运行按钮的编译参数呢?

首先,要知道这个运行按钮是一个VSCode中的C++的插件提供的,这个插件就是: C/C++ Compile Run
然后在它的github主页上有设置参数的方法:

下面就是找到设置这个key的方法。

设置参数的方法

您可以按照以下步骤使用 c-cpp-compile-run.cpp-flags 字段:

  1. 打开 VSCode,然后按下 Ctrl + Shift + P(Windows/Linux)或 Cmd + Shift + P(Mac)打开命令面板。
  2. 输入 “Preferences: Open Workspace Settings” 并选择该选项,以打开当前工作区的设置。
  3. 在设置面板中,搜索 “c-cpp-compile-run.cpp-flags”,然后在这个字段的设置窗口中添加 -std=c++11 这个参数。
    如图:

    问题解决。