DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to the guide
THE FINANCEBASE List yours

Guide

Compile and Run Your First C++ Program on Linux with G++

By TheFinanceBase Team 9 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To compile a first C++ program on Linux, install the GNU compiler packages, save your code as a conventional C++ source file such as hello.cpp, compile it with g++ hello.cpp -o hello, and launch the resulting executable with ./hello. On Ubuntu Desktop, the documented installation command is sudo apt install gcc g++. Other Linux distributions use different package managers and package names.

This guide follows that complete terminal workflow, explains what each command does, shows how to select a predictable C++ language standard, and limits troubleshooting to checks supported by the compiler and its diagnostics.

As an Amazon Associate I earn from qualifying purchases.

What you need before compiling

You need three things:

  • A Linux system with a terminal.
  • A C++ source file saved with a conventional suffix, preferably .cpp for a first exercise.
  • The GNU Compiler Collection (GCC) C++ driver, invoked as g++.

The source file contains human-readable C++ instructions. The compiler translates those instructions into an executable file that Linux can run. Compilation and execution are separate actions: a successful compile creates a file, while a later command starts that file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The GCC documentation recognizes conventional C++ suffixes including .cpp, .cc, and .cxx. Using .cpp makes the language obvious to you and to other people reading the project.

Install or check G++ on Ubuntu Desktop

Install the compiler packages

Ubuntu for Developers documents installation through APT with:

sudo apt install gcc g++

sudo requests administrator permission, and APT installs the repository packages named gcc and g++. Enter your account password when prompted. APT may ask you to confirm the installation; accept only after reviewing the package summary shown by your system.

This command is specifically the Ubuntu Desktop procedure. Do not treat it as a universal Linux command. Fedora, Arch-based systems, openSUSE, Debian derivatives, and other distributions maintain their own package managers, package names, repositories, and version policies. Use the installation instructions for the distribution actually running on your computer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check the installed GCC version

Ubuntu’s documentation uses this check:

gcc --version

The command prints the GCC version selected by your system. The version matters because language defaults and supported C++ standards can differ between GCC generations. If the shell reports that the command cannot be found, the compiler package is not available in your current command path; return to your distribution’s installation instructions before creating a build command.

The g++ executable is installed by the g++ package. If a later compile command reports that g++ cannot be found, check that the package installation completed and read the terminal’s diagnostic text rather than guessing at a source-code problem.

Create a minimal C++ source file

Open a working directory

Choose a directory where you can find both the source and the executable. You can use a graphical text editor or a terminal editor; the important detail is that the file is saved with the exact name hello.cpp in the directory from which you will compile.

For a first program, avoid saving the file as hello.cpp.txt. Some graphical file managers hide known extensions, so confirm the complete filename before compiling. The compiler command must match the actual name and capitalization. Linux filenames are case-sensitive: hello.cpp and Hello.cpp are different names.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
The Psychology of Money: Timeless lessons on wealth, greed, and happiness
  • Ideal for Gifting
  • Ideal for a bookworm
  • Compact for travelling

Enter the program

Save this illustrative source as hello.cpp:

#include <iostream>

int main() {
    std::cout << "Hello, world!n";
    return 0;
}

#include <iostream> makes the standard stream facilities available. The main function is the program entry point. std::cout writes text, and n requests a newline. Returning zero indicates normal completion to the operating system.

This listing is a conventional teaching example. The documented sources establish the compiler driver and command-line workflow; they do not constitute a report that this exact listing was executed on a particular machine.

Compile the file and name the executable

The basic command

From the directory containing hello.cpp, run:

g++ hello.cpp -o hello

Each part has a distinct role:

  • g++ selects GCC’s C++ driver.
  • hello.cpp is the input source file.
  • -o hello tells GCC to write the output executable with the name hello.

If compilation and linking succeed, the command normally returns you to the shell prompt without a success message and creates an executable named hello in the current directory. A diagnostic message instead means the build did not complete; read the message, including its filename and line number, before changing anything.

Why use g++ instead of gcc?

The GCC manual’s description of the C++ driver is direct: “g++ is a program that calls GCC and automatically specifies linking against the C++ library.” That automatic C++ library linking is the key distinction for an ordinary C++ build.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

gcc is the GCC driver commonly used for C, but it does not automatically add the C++ library when you use it for a C++ program. Choosing g++ lets the driver apply the normal C++ compilation and linking behavior without requiring you to add that library manually.

Choice What it does Beginner guidance
g++ hello.cpp -o hello Compiles the C++ source and automatically links the C++ library. Use this for a normal first C++ program.
gcc hello.cpp -o hello Invokes GCC without the C++ driver’s automatic library-linking behavior. Do not substitute it for g++ in this basic workflow.

What -o changes

The -o option controls the output filename. With -o hello, the result is called hello. You could choose another name, such as greeting, by running g++ hello.cpp -o greeting; you would then launch that name with ./greeting. Keeping the source and output names related makes a first project easier to understand.

If you omit -o, GCC chooses its default output name according to its normal driver behavior. Naming the executable explicitly avoids relying on that default and makes the next run command unambiguous.

Run the executable from the current directory

After the compile command completes, start the program with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
./hello

The ./ prefix means “the file named hello in the current directory.” On many Linux systems, the current directory is not searched automatically when you type a bare command name, so hello and ./hello are not interchangeable. The Ubuntu tutorial demonstrates this same compile-then-run pattern with a C example; here it is applied to the named C++ executable.

For the sample program, the displayed line should be:

Hello, world!

The output shown above describes what the source requests; it is not a claim that the listing was run as part of this article.

Use an explicit C++ language standard when it matters

The compiler’s default is version-dependent

A C++ compiler can accept different language dialects. GCC’s current online manual documents -std=gnu++20 as the default dialect. That default is not a promise that every installed GCC release behaves identically: older releases may choose another default or provide a different level of support.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a lesson, assignment, or project expects a particular dialect, make that choice visible in the command rather than relying on an implicit default.

Compile explicitly as GNU C++20

For a program intended to use the GNU C++20 dialect, run:

g++ -std=c++20 hello.cpp -o hello

The -std=c++20 option requests the C++20 language standard without the GNU extensions implied by the documented gnu++20 default. The installed GCC version still determines whether that standard is supported. If an older compiler rejects the option or a feature in the source, consult the version information and the diagnostic output; changing the command blindly will not make an unsupported feature available.

Command form Dialect choice When to use it
g++ hello.cpp -o hello Uses the installed GCC release’s default. Small experiments where the default is acceptable.
g++ -std=c++20 hello.cpp -o hello Requests standard C++20 explicitly. Lessons or projects that specify C++20 and run on a compiler that supports it.

The complete first-program workflow

Once the package is installed and the source file is saved, the shortest repeatable sequence is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Open a terminal and move to the directory containing hello.cpp.
  2. Check the toolchain version with gcc --version if you have not done so already.
  3. Compile and name the output: g++ hello.cpp -o hello.
  4. Run the executable: ./hello.

If the project requires C++20 explicitly, replace step 3 with g++ -std=c++20 hello.cpp -o hello. The output name remains hello, so step 4 does not change.

Understand the files produced

Your working directory contains the source and, after a successful build, the executable:

File Purpose Created by
hello.cpp Human-readable C++ source that you edit. You or your editor.
hello Compiled executable that Linux can launch. The g++ ... -o hello command.

Re-running the same compile command replaces the output executable with a newly built version when compilation succeeds. The source remains the file you edit; the executable is a generated result that can be recreated.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Read compiler diagnostics instead of guessing

If the command itself is missing

A message saying that g++ or gcc cannot be found indicates an installation or command-path issue, not a C++ syntax error. Verify that the Ubuntu package installation completed, or follow the package instructions for your own distribution. Then run gcc --version again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the source file is not found

A diagnostic naming hello.cpp usually means the shell is not in the directory where you saved the file, or the filename differs in spelling or capitalization. Check the file’s exact name and return to the correct directory before repeating the compile command. Do not rename the output or add flags until the input filename is correct.

Best Value
Sale
I Will Teach You to Be Rich: No Guilt. No Excuses. Just a 6-Week Program That Works (Second Edition)
  • It can be a gift option
  • Comes with secure packaging
  • Helpful in various ways

If compilation reports a source error

Read the diagnostic’s filename, line number, and description. Open that line in the source, correct the reported issue, save the file, and run the same compile command again. Compiler diagnostics are the authoritative feedback for the particular source and GCC version in front of you; an error message is more useful than repeatedly changing commands without addressing the indicated line.

If the executable does not start

Confirm that the compile command completed and that you are running the same output name you supplied after -o. If the output was named greeting, the matching command is ./greeting, not ./hello. Also confirm that the terminal is still in the directory containing that executable.

Common first-time mistakes

  • Using gcc for a normal C++ build: use g++ so the C++ library is linked automatically.
  • Forgetting ./: launch a program in the current directory with ./hello.
  • Compiling from the wrong directory: the input filename is resolved relative to the terminal’s current location.
  • Typing a hidden extension: ensure the file is really hello.cpp, not a text file with an additional extension.
  • Assuming every GCC release has the same default: check the installed version and select -std=c++20 when the lesson requires C++20.
  • Changing several things after an error: read the diagnostic first, fix the named source or setup issue, and repeat the smallest command that tests that correction.

What changes on other Linux distributions?

The compile and run commands are generally the same once GCC is installed: save a C++ source file, invoke g++, name the output with -o, and run it with ./. Installation is the part that varies. Ubuntu Desktop documents APT and the package pair gcc g++; another distribution may use a different package manager, package grouping, repository, or compiler version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For that reason, separate “install” advice from the portable build workflow. Find the official package instructions for your distribution, install its C++ compiler tools, verify the GCC version, and then use the source, compile, and run steps described here. Do not assume that an Ubuntu command will work unchanged on a different Linux family.

Quick reference

Goal Command Result
Install on Ubuntu Desktop sudo apt install gcc g++ Requests the Ubuntu repository’s GCC and G++ packages.
Check GCC version gcc --version Prints the installed GCC version.
Compile and name output g++ hello.cpp -o hello Builds an executable named hello.
Compile as C++20 g++ -std=c++20 hello.cpp -o hello Requests the C++20 dialect explicitly.
Run the current-directory executable ./hello Starts the executable named hello.

When your first program is working

Keep the source file as the editable original and treat the executable as a build product. Each time you change the C++ code, save it, rerun the compile command, and then launch the newly generated executable with ./hello. If you need a different language dialect, keep the selected -std= option in the compile command so the build remains explicit and repeatable.

The essential pattern is therefore stable: install the compiler using your distribution’s instructions, use g++ for C++, save conventional source files such as .cpp, name the executable with -o, and invoke that executable with ./ from its directory.

Quick Recap

SaleBestseller No. 1
SaleBestseller No. 2
The Psychology of Money: Timeless lessons on wealth, greed, and happiness
The Psychology of Money: Timeless lessons on wealth, greed, and happiness
Ideal for Gifting; Ideal for a bookworm; Compact for travelling
$10.99
SaleBestseller No. 5
I Will Teach You to Be Rich: No Guilt. No Excuses. Just a 6-Week Program That Works (Second Edition)
I Will Teach You to Be Rich: No Guilt. No Excuses. Just a 6-Week Program That Works (Second Edition)
It can be a gift option; Comes with secure packaging; Helpful in various ways
$9.15

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a comment

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More guides

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.