How to Run C++ Code in VS Code
1. Ensure Your Code is Correct
Open index1.cpp and add std:: before cout and cin:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
2. Compile and Run Manually in VS Code Terminal
1. Open the VS Code terminal (Ctrl + ~).
2. Compile the C++ program:
g++ -o output.exe index1.cpp
3. Run the program:
./output.exe
3. Use the Correct Build Task
1. Open VS Code Settings.
2. Click Terminal > Configure Tasks.
3. Select 'Create tasks.json file from template' > 'Others'.
4. Replace the tasks.json file content with this:
{
"version": "2.0.0",
"tasks": [
{
"label": "Build and Run C++",
"type": "shell",
"command": "g++",
"args": [
"${file}",
"-o",
"${fileDirname}/output.exe"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "Compile and run C++"
}
]
}
4. Set Up a C++ Debugger (Optional)
To debug the program:
1. Press Ctrl + Shift + D (Run & Debug).
2. Click 'Create a launch.json file'.
3. Select 'C++ (GDB/LLDB)'.
4. Use this configuration:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/output.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
5. Try Running in CMD (If VS Code Still Fails)
If VS Code still fails, test it in the Windows Command Prompt:
1. Open Command Prompt (Win + R → type cmd → Enter).
2. Navigate to your file location:
cd C:\Users\USER\Desktop\DUET\PF\Lab_5
3. Compile manually:
g++ -o output.exe index1.cpp
4. Run:
output.exe