The Wayback Machine - https://web.archive.org/web/20240920191845/https://www.geeksforgeeks.org/vs-code-compile-and-run-in-c/
Open In App

VS Code | Compile and Run in C++

Last Updated : 11 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in this article almost automate the process of compilation and execution.

Program:
Let below be the code to demonstrate compilation and execution:

C++




// C++ program to take the input of
// two numbers and prints its sum
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    int a, b;
 
    // Input two numbers
    cin >> a >> b;
 
    // Find the sum
    int sum = a + b;
 
    // Print the sum
    cout << sum;
 
    return 0;
}


Using Integrated Command Line:

For compilation and creation of executable file run the below command:

g++ -std = c++11 -O2 -Wall programName.cpp -o programName.exe 

Understanding different terms in above command:

  • g++: tells the computer the given command is for g++ compiler.
  • -std = c++11: the compiler follows C++11 standard, you can set it to -std = c++14 or -std=c++17 based on what you want to use.
  • -O2: Optimizes the code
  • -Wall: shows warnings about possible errors
  • programName.cpp: refers to the c++ file to be compiled
  • -o programName.exe: creates a executable file of the suggested name( here programName.exe).

Note: The name of cpp file and executable file need not be same.

Steps:

  • Hover over terminal tab and select New Terminal.

  • Command prompt will open with current directory.

  • Type the syntax given above with suitable program-name and executable file name.

  • Press Enter and

Method 1 – Calling Executable File and Managing Input/Output

Input/Output in command line itself:

  • Pass the executable file to be run and press enter.

  • Type the required input, each separated by space and press enter.

  • The required output shall be displayed in a new-line of the command line as shown below.

Input/Output through text files:

  • Create two text files input.txt and output.txt. Make sure input.txt contains the required to be input.

C++




#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif


 

  • Compile the new code again with preferably the same name for executable file.

  • Pass the executable file to be run in the command line and press enter

  • You would notice the output in output.txt file.

Method 2 – Using Code-Runner Extension:

 

Using the template created so far, we can easily upgrade to code runner. Below are the steps:

 

  • Install the code runner extension as shown below:

  • Click on the play button on the top-right of the window as shown below:

  • The output of the program is displayed automatically in output.txt file.

Input/Output using Competitive Programming Helper (cph) extension:

  • Firstly search and install cph by Divyanshu Agrawal

  • Now, we are going to run a simple program and try to show learn how to use this ext.

  • Using +New Testcase, we different test cases and their expected outputs respectively.

  • Using Run All , we run all test cases



Similar Reads

How To Compile And Run a C/C++ Code In Linux
C Programming Language is mainly developed as a system programming language to write kernels or write an operating system. C++ Programming Language is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance. In this article, we will be compiling and executing the C Programming Language codes and also C
3 min read
Difference Between Compile Time And Run Time Polymorphism In C++
In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++. What is Polymorphism? Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms. For example, Your DAD is your father. He's your mom's Husband. He's your grandma's son
4 min read
How to compile 32-bit program on 64-bit gcc in C and C++
Mostly compiler(gcc or clang) of C and C++, nowadays come with default 64-bit version. Well it would be a good option in terms of speed purposes. But it would lead to problem, if someone wants to run their program as a 32-bit rather than 64-bit for testing or debugging purposes. Therefore we must have a knowledge about this.Before proceeding forwar
2 min read
Compile our own Android Kernel in 5 Simple Steps
The Android kernel helps the applications to communicate with the hardware components of the device. For example: Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies. Another example is power saver mode. It instructs the processor and the graphics proce
3 min read
Write a C program that won't compile in C++
Although C++ is designed to have backward compatibility with C, there can be many C programs that would produce compiler errors when compiled with a C++ compiler. Following is the list of the C programs that won’t compile in C++: Calling a function before the declarationUsing normal pointer with const variableUsing typecasted pointersDeclaring cons
4 min read
How to Determine if a Type is an STL Container at Compile Time?
In C++, Standard Template Library (STL) provides many containers such as std::vector, std::list, std::map, and more. What if we want to write a generic code that behaves differently when a given type is an STL container? To do this we need to determine at compile time whether a given type is an STL container or not. In this article, we will learn d
6 min read
VS Code | Build, Run and Debug in C++
In this article, we will discuss the VS Code setup required for break-point debugging. Firstly create a file launch.json that configures the VS Code to launch the GDB debugger at the beginning of the debugging process. Then create a file tasks.json that tells VS Code how to build (compile) the program. Finally, make some changes to the console sett
6 min read
Convert the given RGB color code to Hex color code
Given three colors, such as R, G, and B, convert these RGB color to a hex color code. If the conversion is not possible, print -1. Examples: Input: R = 0, G = 0, B = 0 Output: #000000 Input: R = 255, G = 255, B = 256 Output: -1 Explanation: A 256 color code is not possible as only the 0-255 range is available for a color. Approach: First, check if
9 min read
How can I create a parallel stack and run a coroutine on it?
What is Parallel Stack? A parallel stack is a type of data structure that allows multiple threads to access and manipulate the stack concurrently. In a parallel stack, each thread has its own stack, and all of the stacks are connected in such a way that they can be accessed and manipulated simultaneously. This allows for the efficient use of multi-
4 min read
Run Length Encoding and Decoding
Given an input string, write a function that returns the Run Length Encoded string for the input string.For example, if the input string is "wwwwaaadexxxxxx", then the function should return "w4a3d1e1x6" Recommended PracticeRun Length EncodingTry It! Follow the steps below to solve this problem: Pick the first character from the source string. Appe
4 min read
RTTI (Run-Time Type Information) in C++
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution. Runtime Casts The runtime cast, which checks that the cast is valid, is the
3 min read
Is there any way to determine the available Stack Space at Run Time?
What is stack space? A stack is an area of memory used to temporarily store information in a computer program. It is a common data structure that consists of a series of layers, called frames or levels. Each layer can be one or more cells. The size and number of the various layers are typically then dictated by the computer architecture and archite
6 min read
Guide to deploy containers on Google Cloud Run
Google Cloud Run is one of the fast and scalable solution for your API deployment over secure https connection and can be considered as first choice of every developer. Well firebase is for static websites, right? What if we can deploy Dynamic websites on firebase too? All you need is Cloud Run. Here, in this tutorial we will be showing you how you
3 min read
Run-to-Failure (RTF) Maintenance
Run-to-Failure (RTF) maintenance, also referred to as fit and forget maintenance, is a type of maintenance strategy that follows simple rule i.e. wait until fail. One has to wait till equipment runs to failure i.e. wait until equipment gets failed or gets broken down. After failure, one can fix it or replace it. This is one of cost-effective strate
4 min read
Can Run Time Complexity of a comparison-based sorting algorithm be less than N logN?
Sorting algorithms are the means to sort a given set of data in an order according to the requirement of the user. They are primarily used to sort data in an increasing or decreasing manner. There are two types of sorting algorithms: Comparison-based sorting algorithmsNon-comparison-based sorting algorithms Comparison-based sorting algorithms: The
3 min read
Program to implement Run Length Encoding using Linked Lists
Given a Linked List as the input. The task is to encode the given linked list using Run Length Encoding. That is, to replace a block of contiguous characters by the character followed by it's count. For Example, in Run Length Encoding "a-&gt;a-&gt;a-&gt;a-&gt;a" will be replaced by "a-&gt;5". Note: For non-repeating nodes, do not append count 1. Fo
15+ min read
Does Garbage Collection Guarantee that a Program will not Run Out of Memory?
The work of Garbage collection in Java is to automate the process of deleting memory that's no longer in use. But does that mean Java programs are free from memory limit overflow? Well in this article we will discuss it in brief, but first, let's talk about the garbage collection in Java. Garbage Collection:In C/C++, a programmer is responsible for
3 min read
Run Length Encoding in Python
Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is 'wwwwaaadexxxxxx', then the function should return 'w4a3d1e1x6'. Examples: Input : str = 'wwwwaaadexxxxxx'Output : 'w4a3d1e1x6'This problem has existing solution please refer Run Length Encoding link. Here we
2 min read
Code Optimization Technique (logical AND and logical OR)
Logical AND (&amp;&amp;)While using &amp;&amp; (logical AND), we must put the condition first whose probability of getting false is high so that compiler doesn’t need to check the second condition if the first condition is false. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; // Function to check whether n is odd bool isOdd(int n) {
7 min read
Code valid in both C and C++ but produce different output
There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages. Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++: Example Codes valid
2 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
My Code Frenzy Experience: Challenging Rounds and a Valuable Learning Journey
About the ContestParticipating in coding competitions not only tests your problem-solving skills but also provides a platform for research and development. My recent experience in the "Code Frenzy 1.0" contest, organized by the coding club of my university, "GeeksUnited," inspired by "GeeksForGeeks," was nothing short of exhilarating. This article
5 min read
Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
Given a URL as a string open it using a C++ code in Microsoft Windows OS. Example: Input : https://www.geeksforgeeks.org/ Output : The site opened in your browser. // C++ program to open a URL in browser. // This program is written on for Microsoft // Windows OS #include &lt;bits/stdc++.h&gt; #include &lt;windows.h&gt; using namespace std; int main
5 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code
7 min read
Longest string in non-decreasing order of ASCII code and in arithmetic progression
Given a non-empty string S of uppercase alphabets of length L the task is to find the longest string from the given string with characters arranged in descending order of their ASCII code and in arithmetic progression such that the common difference should be as low as possible and the characters of the string to be of higher ASCII value. Note: The
10 min read
Difference between Low Code Software Development and Traditional Software Development
In this article, we will explore the differences between low code software development and traditional software development. Before diving into the differences, let's first understand what each approach entails. What is Low-Code Software Development?Low-code development involves creating software applications with minimal hand-coding. Instead of wr
6 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read
Morse Code Implementation
Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph. The algorithm is very simple. Every character in the English language is substituted by
9 min read
Compiler Design | Detection of a Loop in Three Address Code
Prerequisite - Three address code in Compiler Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the case of the recursive program a block will be ther
3 min read
Practice Tags :