How to Run C++ Code in VS Code
1. Ensure Your Code is Correct
Open [Link] 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 [Link] [Link]
3. Run the program:
./[Link]
3. Use the Correct Build Task
1. Open VS Code Settings.
2. Click Terminal > Configure Tasks.
3. Select 'Create [Link] file from template' > 'Others'.
4. Replace the [Link] file content with this:
{
"version": "2.0.0",
"tasks": [
{
"label": "Build and Run C++",
"type": "shell",
"command": "g++",
"args": [
"${file}",
"-o",
"${fileDirname}/[Link]"
],
"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 [Link] file'.
3. Select 'C++ (GDB/LLDB)'.
4. Use this configuration:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/[Link]",
"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 [Link] [Link]
4. Run:
[Link]