Run C In Visual Studio Code



Run in Terminal. Now our program will run in the TERMINAL tab and we will be able to enter data if we need to. And that’s it, following these steps you will be able to compile and run code in C/C using Visual Studio Code. So many people getting some issues when they try to run c/c language or any other language code in starting. If you code in VS code (visual studio code), you have to follow these simple steps. download Visual Studio Code on your laptop or de.

  1. Run C In Visual Studio Code Mac
  2. Run C File In Visual Studio Code

Gourav Goyal

By the end of this short guide, you’d be able to run, debug, and get IntelliSense for C/C++ files in VSCode. Though, this guide is focused on the Windows platform but can be extended to Mac and Linux with some minor changes.

I extensively used C & C++ in my competitive programmingyears and wanted better support for debugging & IntelliSense. The only options availablewere Dev-C++ (outdated) and the original 'Mammoth'Visual Studio. Lately, I found VSCode and fell in love with it (first love was Atom).I tweaked it around and set it up as a complete IDE For small C, C++ projects especiallygeared towards competitive programming.

Create a sample C/C++ project

  1. Open/Create an empty folder in VSCode.
  2. Create a new.cpp file inside it like below:
new.cpp
  1. Install recommended C/C++ extension in VSCode and reload.

Install C/C++ Compiler

C/C++ extension does not include a C++ compiler. So, you will need to install one or use which is already installed on your computer.

Windows: Download MinGW64.zip (latest release) and extract it to the C Drive.

Mac:XCode

Linux:GCC

Also, Make sure to add C++ compiler PATH to environment variable of your platform. For Windows MinGW64 add: C:MinGW64bin

Run and Debug C/C++ Code

You’ll notice that there is also a .vscode folder in your sample project. To configure debug configuration, 2 files are required launch.json and tasks.json inside .vscode folder.

VSCode can create and auto-configure these files if we try to debug for the first time. To do that, open C++ file in VSCode and either hit F5 or go to Debug -> Start Debugging and select C++ (GDB/LLDB) then select g++.exe build and debug active file.

This should create 2 files launch.json and tasks.json in .vscode folder which should look like below (update the MinGW64 path if not correct)

Notice that I’ve added one more optional configuration g++ build & run active file in launch.json and g++ build & run in tasks.json file for purpose of also Running C/C++ code without debugging. Now you may choose which configuration to pick when you start debugging. You may remove the configuration whichever you won’t need.

launch.json

tasks.json

tasks.json

externalConsole in launch.json can be set to true to see code output in cmd instead.

Restart VSCode to take effects of newly added compiler paths.

Open any C/C++ file, set some breakpoints (or not), and hit the Big Green Play Button.

(Shortcut to debug: F5 )

Tip: To hide *.exe files in the side explorer of VSCode, open settings and paste the below config:

Thanks for reading. Would love to hear your thoughts about it. Connect with me onTwitter andLinkedIn.

The launch.json file is used to configure the debugger in Visual Studio Code.

Visual Studio Code generates a launch.json with almost all of the required information. To get started with debugging you need to fill in the program field with the path to the executable you plan to debug. This must be specified for both the launch and attach (if you plan to attach to a running instance at any point) configurations.

The generated file contains two sections, one that configures debugging for launch and a second that configures debugging for attach.

Configure VS Code's debugging behavior

Set or change the following options to control VS Code's behavior during debugging:

program (required)

Specifies the full path to the executable the debugger will launch or attach to. The debugger requires this location in order to load debug symbols.

symbolSearchPath

Tells the Visual Studio Windows Debugger what paths to search for symbol (.pdb) files. Separate multiple paths with a semicolon. For example: 'C:Symbols;C:SymbolDir2'.

requireExactSource

An optional flag that tells the Visual Studio Windows Debugger to require current source code to match the pdb.

additionalSOLibSearchPath

Tells GDB or LLDB what paths to search for .so files. Lan scanner for mac. Separate multiple paths with a semicolon. For example: '/Users/user/dir1;/Users/user/dir2'.

externalConsole

Used only when launching the debuggee. For attach, this parameter does not change the debuggee's behavior.

  • Windows: When set to true, it will spawn an external console. When set to false, it will use VS Code's integratedTerminal.
  • Linux: When set to true, it will notify VS Code to spawn an external console. When set to false, it will use VS Code's integratedTerminal.
  • macOS: When set to true, it will spawn an external console through lldb-mi. When set to false, the output can be seen in VS Code's debugConsole. Due to limitations within lldb-mi, integratedTerminal support is not available.

avoidWindowsConsoleRedirection

In order to support VS Code's Integrated Terminal with gdb on Windows, the extension adds console redirection commands to the debuggee's arguments to have console input and output show up in the integrated terminal. Setting this option to true will disable it.

logging

Optional flags to determine what types of messages should be logged to the Debug Console.

  • exceptions: Optional flag to determine whether exception messages should be logged to the Debug Console. Defaults to true.
  • moduleLoad: Optional flag to determine whether module load events should be logged to the Debug Console. Defaults to true.
  • programOutput: Optional flag to determine whether program output should be logged to the Debug Console. Defaults to true.
  • engineLogging: Optional flag to determine whether diagnostic engine logs should be logged to the Debug Console. Defaults to false.
  • trace: Optional flag to determine whether diagnostic adapter command tracing should be logged to the Debug Console. Defaults to false.
  • traceResponse: Optional flag to determine whether diagnostic adapter command and response tracing should be logged to the Debug Console. Defaults to false.

visualizerFile

.natvis file to be used when debugging. See Create custom views of native objects for information on how to create Natvis files.

showDisplayString

When a visualizerFile is specified, showDisplayString will enable the display string. Turning on this option can cause slower performance during debugging.

Example:

Configure the target application

The following options enable you to modify the state of the target application when it is launched:

args

JSON array of command-line arguments to pass to the program when it is launched. Example ['arg1', 'arg2']. If you are escaping characters, you will need to double escape them. For example, ['{'arg1': true}'] will send {'arg1': true} to your application.

cwd

Sets the working directory of the application launched by the debugger.

environment

Environment variables to add to the environment for the program. Example: [ { 'name': 'config', 'value': 'Debug' } ], not [ { 'config': 'Debug' } ].

Visual studio c programming

Example:

Customizing GDB or LLDB

You can change the behavior of GDB or LLDB by setting the following options:

MIMode

Indicates the debugger that VS Code will connect to. Must be set to gdb or lldb. This is pre-configured on a per-operating system basis and can be changed as needed.

miDebuggerPath

The path to the debugger (such as gdb). When only the executable is specified, it will search the operating system's PATH variable for a debugger (GDB on Linux and Windows, LLDB on OS X).

miDebuggerArgs

Additional arguments to pass to the debugger (such as gdb).

stopAtEntry

If set to true, the debugger should stop at the entry-point of the target (ignored on attach). Default value is false.

setupCommands

JSON array of commands to execute in order to set up the GDB or LLDB. Example: 'setupCommands': [ { 'text': 'target-run', 'description': 'run target', 'ignoreFailures': false }].

customLaunchSetupCommands

If provided, this replaces the default commands used to launch a target with some other commands. For example, this can be '-target-attach' in order to attach to a target process. An empty command list replaces the launch commands with nothing, which can be useful if the debugger is being provided launch options as command-line options. Example: 'customLaunchSetupCommands': [ { 'text': 'target-run', 'description': 'run target', 'ignoreFailures': false }].

launchCompleteCommand

The command to execute after the debugger is fully set up in order to cause the target process to run. Allowed values are 'exec-run', 'exec-continue', 'None'. The default value is 'exec-run'.

Example:

symbolLoadInfo

  • loadAll: If true, symbols for all libs will be loaded, otherwise no solib symbols will be loaded. Modified by ExceptionList. Default value is true.
  • exceptionList: List of filenames (wildcards allowed) separated by semicolons ;. Modifies behavior of LoadAll. If LoadAll is true then don't load symbols for libs that match any name in the list. Otherwise only load symbols for libs that match. Example: 'foo.so;bar.so'

Debugging dump files

Run C In Visual Studio Code

The C/C++ extension enables debugging dump files on Windows and core dump files Linux and OS X.

dumpPath

If you want to debug a Windows dump file, set this to the path to the dump file to start debugging in the launch configuration.

coreDumpPath

Full path to a core dump file to debug for the specified program. Set this to the path to the core dump file to start debugging in the launch configuration. Note: core dump debugging is not supported with MinGw.

Remote debugging or debugging with a local debugger server

miDebuggerServerAddress

Network address of the debugger server (for example, gdbserver) to connect to for remote debugging (example: localhost:1234).

debugServerPath

Full path to debug server to launch.

debugServerArgs

Arguments for the debugger server.

serverStarted

Server-started pattern to look for in the debug server output.

serverLaunchTimeout

Time in milliseconds, for the debugger to wait for the debugServer to start up. Default is 10000.

pipeTransport

Studio

Run C In Visual Studio Code Mac

For information about attaching to a remote process, such as debugging a process in a Docker container, see the Pipe transport settings article.

Additional properties

processId

Defaults to ${command:pickProcess} which will display a list of available processes the debugger can attach to. We recommend that you leave this default, but the property can be explicitly set to a specific process ID for the debugger to attach to.

request

Indicates whether the configuration section is intended to launch the program or attach to an already running instance.

targetArchitecture

Deprecated This option is no longer needed as the target architecture is automatically detected.

type

Run C File In Visual Studio Code

Indicates the underlying debugger being used. Must be cppvsdbg when using the Visual Studio Windows debugger, and cppdbg when using GDB or LLDB. This is automatically set to the correct value when the launch.json file is created.

sourceFileMap

This allows mapping of the compile-time paths for source to local source locations. It is an object of key/value pairs and will resolve the first string-matched path. (example: 'sourceFileMap': { '/mnt/c': 'c:' } will map any path returned by the debugger that begins with /mnt/c and convert it to c:. You can have multiple mappings in the object but they will be handled in the order provided.)

Environment variable definitions file

An environment variable definitions file is a simple text file containing key-value pairs in the form of environment_variable=value, with # used for comments. Multiline values are not supported.

The cppvsdbg debugger configuration also contains an envFile property that allows you to easily set variables for debugging purposes.

For example:

project.env file: