Visual Studio Code c++11 extension warning - c++

I am in the process of learning c++ and I'm using visual studio code for Mac. I use Code Runner to run my program. My problem is that when I use something from c++11 like "auto" for variable declaration, visual studio code gives me a warning like this, but if I try running it on Xcode or Eclipse it doesn't:
warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
for(auto y: nstrVec)
This is the program if it's necessary:
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <numeric>
#include <sstream>
int main(){
std::vector<std::string> nstrVec(10);
std::string str("I'm a string");
nstrVec[0] = str;
std::cout << str.at(0) << "\n";
std::cout << str.front() << " " << str.back() << "\n";
std::cout << "Length " << str.length() << "\n";
// copies all characters after the fourth
std::string str2(str, 4);
for(auto y: nstrVec)
if(y != "")
std::cout << y << "\n";
return 0;
}
And this is the c_cpp_proprerties.json file:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/System/Library/Frameworks/Kernel.framework/Versions/A/Headers"
],
"defines": [],
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}

In VS Code:
File>>Preference>>Settings>>Extensions
find C_Cpp>Default:Cpp Standard drop down menu
set that to c++11

I spent so long today trying to figure out why I was getting this error and no where had the exact answer I required so I thought I'd post it here just in case I can save anyone the hassle.
If you're using code runner, look in user settings and set:
"code-runner.executorMap" : { "cpp" : "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt" }
The pertinent bit being "g++ -std=c++17".
This is providing of course you can compile your programme in shell using Daniel's solution above but not in VScode + and using code runner.

I had the same problem, but solved it using set vscode-user-settings <>
"clang.cxxflags": ["-std=c++14"]

I used this to solve my problem. Open your terminal
bash
echo "alias g++='g++ -std=c++17'" >> ~/.bashrc
source ~/.bashrc
zsh
echo "alias g++='g++ -std=c++17'" >> ~/.zshrc
source ~/.zshrc

For everyone who comes to this question to find a quick answer (like I did):
The following compiler command should compile your program main.cpp with the latest C++ standard (c++17) and should get rid of warning messages like the one described above:
g++ -std=c++17 -g main.cpp -o main
It is mentioned multiple times in the comments, but I think this question should have a regular answer.

If you're using CPH judge extension in VS add -std=c++11 in Cph › Language › Cpp: Args in extension settings

If you're using CPH, add this line to Cph >> Language >> Cpp: Args
-std=c++17
If it doesn't work for you, also go to File >> Preference >> Settings >>
Extensions >> C_Cpp >> Default:Cpp_Standard and set that to c++17

None of the answers here worked for me on Mac that were entirely within VSCode (I didn't want to modify my .zshrc file).
What did work though, was adding argument --std=c++20 for the clangd: Fallback Flags under Extensions > clangd, then restarting VSCode.

Fix for MAC + code runner.
Select Code -> Settings -> Settings
In the search prompt, seach "code-runner":
Click on "Edit settings.json"
Look for a field called "code-runner.executorMap" -> "cpp"
After g++, add the following to it " -std=c++17 ". In other words, the line should look something like this:
"cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt &&
$dir$fileNameWithoutExt"
Close VSCode, and open it again.

Related

Can't configure Visual Studio Code to use C++14 standard (C++03 standard is used even though I changed some settings)

I did a very simple app that works when I build and run it from the terminal by:
g++ -std=c++14 helloworld.cpp
./a.out
Now I'm trying to configure the Visual Studio Code to debug this app. I did:
Settings -> search for "cppStandard" -> changed to c++14 for both User & Workspace
Add Debug configuration -> C/C++: g++ build and debug active file
Select -> Debug C/C++ file.
error showing:
'function\<void ()\>' is deprecated: Using std::function in C++03 is not supported anymore. Please upgrade to C++11 or later, or use a different type \[-Wdeprecated-declarations\]
The IDE also marks the code:
std::function<void()> func = []() { std::cout << "From Thread ID : "<<std::this_thread::get_id() << "\n"; };
as an error, showing:
class std::__1::function<void ()> 'function<void ()>' is deprecated: Using std::function in C++03 is not supported anymore. Please upgrade to C++11 or later, or use a different type [-Wdeprecated-declarations]gcc
Edited:
I'm using macOS Ventura with apple silicon.
I have added c_cpp_properties.json (by: Control+Shift+P -> c/c++ edit configuration).
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"intelliSenseMode": "macos-clang-arm64",
"cppStandard": "c++14"
}
],
"version": 4
}
I still get the same error about C++03 not compatible with my code, Any suggestions?

VSCode ignores cpp standard when folder is opened in WSL: Ubuntu?

When I open a folder with WSL: Ubuntu and then try to build the project it seems to ignore the cpp standard set in VSCode's User settings. I can choose the standard I want by configuring a task.json file however I want to know how to change the default cpp standard for any folder opened in VSCode with WSL: Ubuntu. I have tried adding the following in my User settings in VSCode.
...
"C_Cpp.default.cppStandard": "c++17",
...
"code-runner.executorMap": {
...
"cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
...
},
And yet when I build the following and execute the output I get 201402 indicating it is using c++14.
#include <iostream>
int main()
{
std::cout << __cplusplus << std::endl;
return 0;
}
Any suggestions on how to change the default c++ standard?
It seems that if I open the file in windows then it works fine as well so I don't know what the difference is here?

Compiling a cpp file with vscode, in Ubuntu

I'm trying to follow this link on how to get started with c++ and vscode in ubuntu.
I have gcc already installed with the latest version.
Running sudo apt-get install build-essential gdb gives:
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.8ubuntu1.1).
build-essential set to manually installed.
gdb is already the newest version (9.2-0ubuntu1~20.04.1).
gdb set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
However, when I get to the stage of creating the config file, I have no option for C/C++: g++ build active file. I only have
So, I choose /usr/bin/cpp.Then I build the file, and get the success message.
However, when run the newly created executable file, I get several error messages:
./helloworld: line 17: namespace: command not found
./helloworld: line 23: syntax error near unexpected token `('
./helloworld: line 23: ` typedef decltype(nullptr) nullptr_t;'
the strange thing is that the lines with code in the helloworld file end on line 16, so I think there's something wrong with the compiler...
Its best to get GCC working in your commandline, then get it working using VS Code tasks.
I suggest that you create the most simplistic project structure you can. Use only a project directory, and a single file named main.cpp.
Something that looks like this:
PROJECT (dir) // path = ./
│
└──> main.cpp (file) // path = ./main.cpp
Once you have a directory with main.cpp do 1 of 2 things:
Use the following command to add a Hello World example to your main.cpp file.
$> echo -e "\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n cout << \"Hello World\!\" << endl;\n}" > main.cpp
Or copy and paste the code below into main.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
}
FYI: You should be doing this from the command-line not vscode (not until you create the vscode task which I will show bellow)
Another thing to note, is your commandline should be pointed to your project directory, the directory you created with main.cpp in it.
From inside your project directory execute the following command.
$> g++ ./main.cpp -o build
if your file compiled & built your executable correctly you should be able to use the ls command to see a new file named build in your project directory.
If all went well, the new build file is an executable. Execute it by entering...
$> ./build
and you should see "Hello World!"
At this point use the following command...
$> code .
VS Code should open to your projects directory.
Now using vscode create another directory, and name it ./.vscode
Then add a file to the ./.vscode directory named tasks.json
The files full pathname will be: ./.vscode/tasks.json
then you will want to add the following to your tasks file
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "GCC: My Compilation Task",
"command": "/usr/bin/g++",
"args": ["-g", "./main.cpp", "-o", "./build"],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
then you should be able to press F1 and type RUN TASK, when you see the option in the quick menu that says RUN TASK click it, and then select the tasks with the same name as the label key in your tasks.json file, which is "GCC: My Compilation Task"

Run C and C++ on VS Code (and even a little problem with vs code bars)

i have some problems:
i cant run c and c++ on vs code (or, i mean im trying by adding the path of MinGW on env vars, but no results by typing on cmd gdb --version, but i have by typing g++ --version)
aaand i just hided this bar by mistake, how to adjust? thanks to everyone!
1- Add to the path variable the directory of the bin folder of MinGW.
Ex: C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin
2- Check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type:
g++ --version
OR
gdb --version
3- Create helloworld.cpp:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
4- Save
5- From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a tasks.json file:
6- To run the code:
Save helloworld.cpp
press Ctrl+Shift+B or from the Terminal main menu choose Run Build Task
You should see this in the terminal:
Create a new terminal using the CTRL + SHIFT + ~
In that new terminal type: .\helloworld.exe to run the code
Reference: C++ in VS-code

Opencv C++ MinGW VSCode fatal error to compile

Hi all I want to use VSCode MinGW C++ and OpenCV to create a simple opencv project but for an unknown reason, I get this error what should I do?
I want to mention that in Visual studio 2017 works I can run the main.cpp on x64 architecture.
The code below is what I want to run on VSCode is the same code I run on the Visual Studio 2017.
After 10 days of trying I give up 50 points if someone proves that with:
VSCODE
C++17
Opencv
on Windows 10 x64 Architecture
A successful build.
src/main.cpp
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat image;
image = imread("./22.png", IMREAD_COLOR); // Read the file
namedWindow("Display window", WINDOW_AUTOSIZE); // Create a window for display.
if (!image.data) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl;
} else { // Image is good!
imshow("Display window", image); // Show our image inside it.
}
waitKey(0);
return 0;
}
In my VSCode editor, I try to build the application using the tasks.json with CTRL + SHIFT + B
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "",
"args": [
"g++",
"-I", "C:\\vcpkg\\installed\\x64-windows\\include",
"-L", "C:\\vcpkg\\installed\\x64-windows\\lib",
"./src/main.cpp",
"-lopencv_core341",
"-lopencv_highgui341",
"-o app"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/src",
"C:/vcpkg/installed/x64-windows/include",
"C:/vcpkg/installed/x64-windows/lib"
],
"browse": {
"path": [
],
"limitSymbolsToIncludedHeaders": true
},
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.17134.0",
"compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.14.26428/bin/Hostx64/x64/cl.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "msvc-x64",
"C_Cpp.intelliSenseEngine": "Tag Parser"
}
],
"version": 4
}
And I get this error
> Executing task: g++ main.cpp -I C:/vcpkg/installed/x64-windows/include -L C:/vcpkg/installed/x64-windows/lib -lopencv_core341 -lopencv_highgui341 -o app <
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text+0x51): undefined reference to `cv::imread(cv::String const&, int)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text+0xa2): undefined reference to `cv::namedWindow(cv::String const&, int)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text+0x119): undefined reference to `cv::imshow(cv::String const&, cv::_InputArray const&)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text+0x139): undefined reference to `cv::waitKey(int)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text$_ZN2cv6StringC1EPKc[__ZN2cv6StringC1EPKc]+0x42): undefined reference to `cv::String::allocate(unsigned int)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text$_ZN2cv6StringD1Ev[__ZN2cv6StringD1Ev]+0xf): undefined reference to `cv::String::deallocate()'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text$_ZN2cv3MatD1Ev[__ZN2cv3MatD1Ev]+0x2d): undefined reference to `cv::fastFree(void*)'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text$_ZN2cv3Mat7releaseEv[__ZN2cv3Mat7releaseEv]+0x40): undefined reference to `cv::Mat::deallocate()'
C:\Users\giorg\AppData\Local\Temp\ccNFIHQq.o:main.cpp:(.text$_ZN2cv3MataSEOS0_[__ZN2cv3MataSEOS0_]+0xb4): undefined reference to `cv::fastFree(void*)'
collect2.exe: error: ld returned 1 exit status
The terminal process terminated with exit code: 1
Terminal will be reused by tasks, press any key to close it.
I have generated the opencv libs using the vcpkg using this command vcpkg install opencv and I think is doing the job very well.
After I generated all the files with the vspkg I test all the files with Visual Studio 2017 and is works, but my main goal is to make work with the VSCode but I don't have any clue why I get the errors.
To show you that I have generated the files.
C:\vcpkg\installed\x64-windows\include
C:\vcpkg\installed\x64-windows\include\opencv2
C:\vcpkg\installed\x64-windows\lib
I have success trying to build and run a C++ program with OpenCV 3.4.1 using MinGW-w64 g++ in Visual Studio Code on Windows 10 x64. But I don't know if this is actually the "right" way to do it.
Screenshot
Download and Install MinGW-w64 choose x86_64-8.1.0-posix-seh-rt_v6-rev0 version or newer http://mingw-w64.org/doku.php/start.
Open CMD and go to C:\ then clone this repo https://github.com/huihut/OpenCV-MinGW-Build then checkout the OpenCV-3.4.1-x64 branch or just execute this git clone https://github.com/huihut/OpenCV-MinGW-Build.git -b OpenCV-3.4.1-x64
Add Mingw-w64 bin folder to the system path (For me the path is C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin)
Add OpenCV mingw bin folder that you clone earlier to the system path (For me the path is C:\OpenCV-MinGW-Build\x64\mingw\bin)
For now you can already build a program using g++ using CMD just type g++ test.cpp -IC:\OpenCV-MinGW-Build\include -LC:\OpenCV-MinGW-Build\x64\mingw\bin -llibopencv_calib3d341 -llibopencv_core341 -llibopencv_dnn341 -llibopencv_features2d341 -llibopencv_flann341 -llibopencv_highgui341 -llibopencv_imgcodecs341 -llibopencv_imgproc341 -llibopencv_ml341 -llibopencv_objdetect341 -llibopencv_photo341 -llibopencv_shape341 -llibopencv_stitching341 -llibopencv_superres341 -llibopencv_video341 -llibopencv_videoio341 -llibopencv_videostab341 just change the test.cpp to your .cpp file name.
Open your .cpp file using Visual Studio Code then install Code Runner extension https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner, I use Code Runner to easily run my program.
Press Ctrl + comma in Visual Studio Code then search for "code-runner.executorMap": and change the content on"cpp:" entry to "cd $dir && g++ $fileName -o $fileNameWithoutExt -IC:/OpenCV-MinGW-Build/include -LC:/OpenCV-MinGW-Build/x64/mingw/bin -llibopencv_calib3d341 -llibopencv_core341 -llibopencv_dnn341 -llibopencv_features2d341 -llibopencv_flann341 -llibopencv_highgui341 -llibopencv_imgcodecs341 -llibopencv_imgproc341 -llibopencv_ml341 -llibopencv_objdetect341 -llibopencv_photo341 -llibopencv_shape341 -llibopencv_stitching341 -llibopencv_superres341 -llibopencv_video341 -llibopencv_videoio341 -llibopencv_videostab341 && $dir$fileNameWithoutExt", you can apply this for user settings or just for workspace settings.
`
After that just press Ctrl+Alt+N to Build and Run your program or just press the play button.
I believe you can also apply this to the tasks.json by adding the -IC:\OpenCV-MinGW-Build\include .. to the args part to use the Visual Studio Code C/C++ extension debugging. Also you can add "C:/OpenCV-MinGW-Build/include" to the c_cpp_properties.json include path to enable intellisense. If you want to use another version of OpenCV just replace all the "341" part of the g++ argument to another version for example to use OpenCV 3.3.1 use -llibopencv_calib3d331 and so on.
EDIT: I have try to edit my tasks.json and launch.json and it works with gdb debugger.
tasks.json : https://gist.github.com/agtbaskara/4a2ec9a3a9a963069e719c0477185321
launch.json : https://gist.github.com/agtbaskara/de04db8b6a31522dd1e62c43aa6e0f89
c_cpp_properties.json : https://gist.github.com/agtbaskara/0eb773ac3085557baf7bf20b031fb49e
Here are instructions for setting up OpenCV in MSYS2/mingw64. I can't help with VsCode but perhaps this will help you make progress, or help other people who find this question by searching.
You don't need to actually build OpenCV yourself; there are prepackaged binaries for MinGW-w64. The purpose of MSYS2 is to provide a unix-style shell and act as a package manager. If you haven't used MSYS2 before:
Install MSYS2 and update to latest as shown here.
Open a MSYS2/mingw64 shell (not a MSYS2/msys2 shell). Binaries built in this shell will run as standalone Windows binaries, they do not depend on the MSYS2 environment.
Test that g++ works.
Then you can add OpenCV:
pacman -Ss mingw64/mingw-w64-x86_64-opencv
and it's all ready to go. I compiled your sample program using the following command in MSYS2 shell:
g++ -o main main.cpp -std=c++17 -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc
and ran the program successfully.
Note that you do not need to use MSYS2 for the build environment; you can invoke g++ from Windows Command Prompt or from any other IDE if you set up the Include and Library paths to point to where MSYS2's package manager installed the headers and libraries. (Which is under /mingw64/include/opencv* and /mingw64/lib , under the MSYS2 installation root).
Install vcpkg ( MS packager to install windows based open source projects) and use powershell command .\vcpkg install opencv:x64-windows-static. Dependency libraries will be auto installed for you.
Opencv can be auto integrated into your VS project using .\vcpkg integrate install.