In this lab, you will learn how to write your first C++ program. You will start by installing the GCC (GNU Compiler Collection) compiler and configuring the necessary environment variables on Ubuntu 22.04. Then, you will create a new C++ source file, write the basic program structure, and use the cout statement to print the "Hello World" message. You will also learn how to compile and execute the program, as well as how to add single-line and multi-line comments, use endl and \n for line breaks, and fix common syntax errors like missing semicolons.
Skills Graph
%%%%{init: {'theme':'neutral'}}%%%%
flowchart RL
cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"])
cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"])
cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"])
cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"])
cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`")
cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`")
cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`")
cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`")
cpp/ControlFlowGroup -.-> cpp/if_else("`If...Else`")
cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`")
cpp/BasicsGroup -.-> cpp/variables("`Variables`")
cpp/BasicsGroup -.-> cpp/strings("`Strings`")
subgraph Lab Skills
cpp/output -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/comments -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/user_input -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/files -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/if_else -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/code_formatting -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/variables -.-> lab-446069{{"`Write Your First C++ Program`"}}
cpp/strings -.-> lab-446069{{"`Write Your First C++ Program`"}}
end
Install GCC Compiler and Configure Environment Variables on Ubuntu 22.04
In this step, you'll learn how to install the GCC (GNU Compiler Collection) compiler for C++ and configure the necessary environment variables on Ubuntu 22.04. GCC is essential for compiling and running C++ programs.
First, let's open the terminal in the WebIDE. You can do this by clicking on the terminal icon at the bottom of the screen or using the keyboard shortcut (usually Ctrl+`).
We'll start by updating the package list to ensure we have the latest information about available packages:
sudo apt update
Example output:
Hit:1 http://mirrors.cloud.aliyuncs.com/ubuntu jammy InRelease
Hit:2 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates InRelease
Hit:3 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-backports InRelease
Hit:4 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security InRelease
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
157 packages can be upgraded. Run 'apt list --upgradable' to see them.
Next, we'll install the GCC compiler and related development tools:
sudo apt install -y build-essential
Example output:
Reading package lists...
Building dependency tree...
Reading state information...
build-essential is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 22 not upgraded.
To verify the installation and check the GCC version, run:
g++ --version
Example output:
g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
The GCC compiler is typically already in the system PATH, so no additional configuration is needed.
Create a New C++ Source File with .cpp Extension
In this step, you'll learn how to create a new C++ source file with the .cpp extension. In C++, source files use the .cpp extension to indicate that they contain C++ code. We'll use the WebIDE's file explorer and text editor to create our first C++ source file.
First, navigate to the ~/project directory in the terminal:
cd ~/project
Now, open the WebIDE's file explorer. You'll see a sidebar with a list of files and folders. Look for an icon that allows you to create a new file - it might look like a "+" sign or "New File" option.
Right-click in the file explorer and select "New File". When prompted, name the file hello.cpp. The .cpp extension is crucial as it tells the compiler and development tools that this is a C++ source file.
Example file creation in terminal (for reference):
touch hello.cpp
Click on the newly created hello.cpp file to open it in the WebIDE's text editor. You'll see an empty file ready for your first C++ code.
The .cpp extension is important because:
It identifies the file as a C++ source code file
Helps development tools and compilers recognize the file type
Distinguishes C++ files from other programming language files like .c (C), .java (Java), or .py (Python)
At this point, your hello.cpp file is ready for you to start writing C++ code. In the next steps, you'll learn how to write a basic C++ program in this file.
Write Basic Program Structure with int main() Function
In this step, you'll learn about the fundamental structure of a C++ program, focusing on the main() function. Every C++ program must have a main() function, which is the entry point where the program starts executing.
Open the hello.cpp file in the WebIDE that you created in the previous step. We'll now add the basic program structure:
#include <iostream>
int main() {
// Your code will go here
return 0;
}
Note: Hand typing the code is recommended for better learning outcomes. Becareful with the curly braces { } and semicolons ; as they are essential in C++ syntax. Don't forget the spaces and indentation, otherwise, step verification may fail.
Let's break down this basic structure:
#include <iostream>: This is a preprocessor directive that includes the input/output stream library. It allows us to use input and output operations like printing to the screen.
int main(): This is the main function declaration
int specifies that the function will return an integer value
main() is the standard entry point for C++ programs
The empty parentheses () indicate that the function takes no arguments
Curly braces { }: Define the body of the function where your code will be written
return 0;: Indicates successful program completion
Returning 0 tells the operating system that the program ran without errors
This is a standard practice in C++ programs
WebIDE will automatically save your changes as you type. Or, you can manually save the file using the editor's save option.
If you want to learn more about the WebIDE, check out the WebIDE Guide.
Some important points to remember:
Every C++ program must have a main() function
The main() function is where the program execution begins
The return 0; statement is typically used to indicate successful program execution
You can think of the main() function like the starting point of a journey. Just as a road trip begins at a specific location, a C++ program begins its execution at the main() function.
Use cout to Print Hello World Message
In this step, you'll learn how to use cout to print a "Hello, World!" message to the screen. cout is part of the C++ standard input/output library and is used to display output.
Open the hello.cpp file in the WebIDE and modify the main() function to include the following code:
std::cout: This is the standard output stream object
std:: indicates we're using the standard namespace
cout stands for "console output"
<<: The stream insertion operator, used to send data to the output stream
"Hello, World!": The text message we want to print
std::endl: Adds a new line and flushes the output buffer
Ensures the message is immediately displayed
Moves the cursor to the next line
When you save the file, make sure to include the entire structure shown above.
Some key points about cout:
It's used to print text, numbers, and other data types to the screen
The << operator can be chained to print multiple items
std::endl is used to create a new line after printing
You can think of cout like a megaphone that announces your message to the world. The << operator helps you load the message, and std::endl makes sure everyone hears it clearly.
Compile Program with g++ hello.cpp -o hello Command
In this step, you'll learn how to compile your C++ program using the g++ compiler. Compilation is the process of converting your human-readable C++ source code into an executable program that the computer can run.
Open the terminal in the WebIDE. Make sure you're in the ~/project directory:
cd ~/project
Now, let's compile the hello.cpp file you created earlier using the g++ command:
g++ hello.cpp -o hello
Let's break down this command:
g++: The GNU C++ compiler
hello.cpp: The source file you want to compile
-o hello: Specifies the output executable name
-o is an option that lets you name the output file
hello is the name of the executable you'll create
Example output:
## No output means successful compilation
If the compilation is successful, no error messages will be displayed. The compiler creates an executable file named hello in the same directory.
To verify the compilation, you can check the files in the directory:
ls
Example output:
hello hello.cpp
You should now see two files:
hello.cpp: Your source code file
hello: The compiled executable program
Some important compilation notes:
If there are any errors in your code, g++ will display error messages
Always check and fix any compilation errors before trying to run the program
The -o option is optional, but it's a good practice to give your executable a meaningful name
You can think of compilation like translating a book from one language to another. The g++ compiler translates your human-readable C++ code into a language the computer can understand and execute.
Execute Program with ./hello Command
In this step, you'll learn how to run the executable program you just compiled. After compiling your C++ program, you can execute it using the ./ command followed by the executable name.
Make sure you're in the ~/project directory:
cd ~/project
To run the program you compiled in the previous step, use the following command:
./hello
The ./ tells the system to look for the executable in the current directory, and hello is the name of the executable you created.
Example output:
Hello, World!
Let's break down what's happening:
./ means "in the current directory"
The program reads the instructions in your compiled executable
It prints the message you defined in your C++ source code
After printing, the program exits
Some important execution notes:
Always use ./ before the executable name when running a program in the current directory
The program must have execute permissions (which g++ automatically provides)
If you don't see the output, double-check that you compiled the program correctly
You can think of executing a program like starting a car. Compilation is preparing the car, and running the program is turning the key and driving.
If you want to run the program multiple times, you can simply repeat the ./hello command.
Add Single-line and Multi-line Comments
In this step, you'll learn how to add comments to your C++ code. Comments are notes in your code that explain what the code does. They are ignored by the compiler and help make your code more readable.
Open the hello.cpp file in the WebIDE and modify it to include different types of comments:
#include <iostream>
// This is a single-line comment
// It explains what the program does
/*
This is a multi-line comment
You can write multiple lines of explanation
Without worrying about adding // to each line
*/
int main() {
// Print a greeting message
std::cout << "Hello, World!" << std::endl; // Inline comment explaining the output
/*
You can also use multi-line comments
in the middle of your code if needed
*/
return 0; // Return success status to the operating system
}
Let's break down the types of comments:
Single-line comments:
Start with //
Extend to the end of the line
Great for short explanations
Multi-line comments:
Start with /*
End with */
Can span multiple lines
Useful for longer explanations
Inline comments:
Added at the end of a code line
Explain the specific line of code
Compile and run the program to verify it still works:
g++ hello.cpp -o hello
./hello
Example output:
Hello, World!
Some key points about comments:
Comments make your code more understandable
They help other programmers (and yourself) understand the code's purpose
The compiler completely ignores comments
Use comments to explain "why" something is done, not "what" is being done
You can think of comments like sticky notes in a book. They provide extra context and explanation without changing the actual text.
Use endl and \n for Line Breaks
In this step, you'll learn two ways to create line breaks in C++ output: std::endl and the newline character \n. Both methods help you format your output across multiple lines.
Open the hello.cpp file in the WebIDE and modify it to demonstrate line breaks:
#include <iostream>
int main() {
// Using std::endl for line breaks
std::cout << "Hello, World!" << std::endl;
std::cout << "Welcome to C++ Programming!" << std::endl;
// Using \n for line breaks
std::cout << "Using newline character:\n";
std::cout << "Line 1\n";
std::cout << "Line 2\n";
// Mixing both methods
std::cout << "Mixing methods: " << std::endl;
std::cout << "Line with endl\n";
std::cout << "Line with newline character" << std::endl;
return 0;
}
๐ LabEx Tips: Click "Explain Code" at the bottom right of the code block to chat with Labby AI for code clarification.
Let's break down the line break methods:
std::endl:
Adds a new line
Flushes the output buffer (ensures immediate printing)
Part of the <iostream> library
Used with std::cout
\n (Newline character):
Simple way to create a new line
Lighter weight than std::endl
Works in many programming contexts
Does not flush the output buffer
Compile and run the program:
g++ hello.cpp -o hello
./hello
Example output:
Hello, World!
Welcome to C++ Programming!
Using newline character:
Line 1
Line 2
Mixing methods:
Line with endl
Line with newline character
Key points:
Both std::endl and \n create new lines
std::endl is more comprehensive but slightly slower
\n is faster and more lightweight
You can mix and match these methods
You can think of line breaks like paragraph breaks in a book. They help organize and structure your output.
Fix Common Syntax Errors like Missing Semicolons
In this step, you'll learn about common syntax errors in C++, with a focus on missing semicolons. Semicolons are crucial in C++ as they mark the end of statements.
Create a new file called syntax_errors.cpp in the WebIDE:
cd ~/project
touch syntax_errors.cpp
#include <iostream>
int main() {
// Common syntax error: Missing semicolon
std::cout << "This line has an error" // Missing semicolon here!
std::cout << "This line will not compile" << std::endl;
// Correct version with semicolons
std::cout << "This line is correct" << std::endl;
std::cout << "All statements end with a semicolon" << std::endl;
return 0; // Don't forget the semicolon here too!
}
Try to compile the program:
g++ syntax_errors.cpp -o syntax_errors
Example compilation error:
syntax_errors.cpp: In function โint main()โ:
syntax_errors.cpp:5:42: error: expected โ;โ before โstdโ
5 | std::cout << "This line has an error" // Missing semicolon here!
| ^
| ;
6 | std::cout << "This line will not compile" << std::endl;
| ~~~
Key points about semicolons:
Every statement in C++ must end with a semicolon ;
Semicolons tell the compiler where one instruction ends and another begins
You can think of semicolons like periods in a sentence. They mark the end of a complete thought in your code.
Summary
In this lab, you will learn how to install the GCC (GNU Compiler Collection) compiler for C++ and configure the necessary environment variables on Ubuntu 22.04. You will create a new C++ source file, write a basic program structure with the int main() function, and use cout to print the "Hello World" message. You will then compile the program using the g++ command and execute it. Additionally, you will learn how to add single-line and multi-line comments, use endl and \n for line breaks, and fix common syntax errors such as missing semicolons.
After completing these steps, you will have a solid foundation for writing and running your first C++ program, as well as an understanding of the basic tools and concepts required for C++ development on Ubuntu 22.04.
We use cookies for a number of reasons, such as keeping the website reliable and secure, to improve your experience on our website and to see how you interact with it. By accepting, you agree to our use of such cookies. Privacy Policy