如何在VS Code中消除[-Wc++11-extensions]编译警告?
Hey there, let's sort out how to fix this warning permanently in VS Code instead of typing the -std=c++11 flag every time on the command line.
First, the root cause: Initializing non-static class members directly inside the class (like myCurrentTry = 1 and myMaxTries = 5) is a feature introduced in C11. Your compiler's default standard is probably set to an older version (like C98), which is why you're getting that compatibility warning. Below are two key configurations to fix both compilation and editor-level warnings:
1. Configure the Build Task (tasks.json)
This ensures VS Code automatically adds the -std=c++11 flag when compiling your code, eliminating the warning during the build process:
- Press
Ctrl+Shift+B(Windows/Linux) orCmd+Shift+B(Mac). If you don't have a build task yet, select "Create tasks.json file" and pick your compiler (GCC or Clang). - In the generated
tasks.json, find theargsarray and add"-std=c++11"to the list. Here's what the modified section looks like:
{ "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-std=c++11", // Add this line "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": ["$gcc"], "group": {"kind": "build", "isDefault": true}, "detail": "Compiler: /usr/bin/g++" } ] }
- Save the file, and your next build won't throw that warning anymore.
2. Configure IntelliSense (c_cpp_properties.json)
This fixes the real-time warning underline in the VS Code editor by telling IntelliSense to recognize C++11 standards:
- Press
Ctrl+Shift+P(Windows/Linux) orCmd+Shift+P(Mac), search for "C/C++: Edit Configurations (JSON)" and open the file. - In the
configurationsarray, set thecppStandardfield to"c++11". Example:
{ "configurations": [ { "name": "Linux", "includePath": ["${workspaceFolder}/**"], "defines": [], "compilerPath": "/usr/bin/g++", "cStandard": "c17", "cppStandard": "c++11", // Update this line "intelliSenseMode": "linux-gcc-x64" } ], "version": 4 }
- Save the file, and the editor's warning should disappear immediately.
Quick Extra Tip
If you want to use newer C++ standards (like C17 or C20), just replace "c++11" with the standard version you prefer—this will still resolve the original warning and unlock more modern C++ features.
内容的提问来源于stack exchange,提问作者Brittany Garcia

