To run C and C++ code in Visual Studio Code (VS Code), you need to follow these steps:
1. Install VS Code and Extensions
- Download and install Visual Studio Code.
- Open VS Code and go to the Extensions view by clicking on the square icon in the sidebar or pressing
Ctrl + Shift + X
. - Search for C/C++ and install the extension provided by Microsoft.
- Install Code Runner (optional but useful) to quickly run code snippets.
2. Install a C/C++ Compiler
- Windows: Install MinGW or MSYS2. You can download MinGW from MinGW-w64 or MSYS2.
- After installation, add the compiler to your system’s PATH environment variable.
- macOS: Install the Xcode Command Line Tools by running
xcode-select --install
in the Terminal. - Linux: Install GCC by running
sudo apt update && sudo apt install build-essential
(for Debian-based systems) orsudo yum groupinstall "Development Tools"
(for Red Hat-based systems).
3. Set Up Your Compiler Path in VS Code (If Needed)
- Go to File > Preferences > Settings, search for C_Cpp: Default Compiler Path, and enter the path of your installed compiler.
4. Write C/C++ Code
- Create a new file with the
.c
or.cpp
extension, for example,hello.c
orhello.cpp
. - Write your C or C++ code in this file.
5. Configure Tasks for Building C/C++ Programs
-
Go to Terminal > Configure Default Build Task... > C/C++: g++ build active file.
-
This will create a
tasks.json
file in a.vscode
folder within your workspace. -
Make sure the
tasks.json
file looks like this:
6. Run the Code
- To build and run your code, press
Ctrl + Shift + B
to compile the code. - Go to Terminal > New Terminal and type the following command to run the executable:
- If you installed Code Runner, you can also right-click the editor and select Run Code to compile and run in one step.
Optional: Debugging
- For debugging, you need to install gdb (GNU Debugger) if it’s not installed already.
- In VS Code, go to Run > Add Configuration and set up a C/C++ debug configuration to use debugging tools like breakpoints, step-through execution, etc.
These steps should set you up to write, build, and run C and C++ code in VS Code efficiently.
Comments
Post a Comment
Thank you for your message.