How to Create and Run a Program in C++
C++ is an object oriented programming language developed by Bjarne Stroustrup, as an extension to the C language.
To create a program in C++, you need to have two things in your computer:
- A compiler to translate the code a computer can understand.
- A text editor to write a program.
Through out this tutorial, we will use Visual Studio Code as a text editor to write a program and GCC compiler to translate a program.
Follow the steps below to create and run your first program in C++:
- Create a project folder in your preferred project workspace directory using terminal command mkdir project_folder_name. Example:
- Add your newly created project folder to Project Explorer of the Visual Studio Code IDE. Go to the main menu, choose File > Add Folder to Workspace > Add your project folder.
- When your project appears in the Project Explorer, right-click the project folder and then click the New File.
- Type the name of the file with .cpp extension and then press enter to create the file. Example my_first_program.cpp
- Open the .ccp file in the Visual Studio Code editor and add the following code:
- Save the file.
- To run the program, right-click the .cpp file and choose > Run Code from the menu item.
- If the code is valid, you should see the output like this:
mkdir my_learning_project
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
In this example program, we have imported an iostream header file . This header file contains functions to handle the input and output stream in C++. std namespace is the standard namespace which contains built-in class and functions. main( ) is the main function of the program. To get our program executed, we need to call this function. We have declared “int” in the main function. This means our program should return an integer value. We do it by returning 0 at the end of the main function. return 0 indicates the program to return 0 when execution reaches that line of the code. To print the output in the console, cout is used. The cout in C++ is an object of class iostream that is used to display output in the console.