File types · Explainer

The C++ source file (.cpp, .cc, .cxx)

A C++ file is a plain-text file of source code in the C++ programming language, which a compiler turns into a program you can run. This guide explains what's inside one, how to compile it on each system, the C++ standards and the errors people hit most, and has free sample C++ files to download for testing.

At a glance

Full name
C++ source file
Extensions
.cpp, .cc, .cxx, .c++ (and .C on case-sensitive systems); headers .hpp, .hh, .h
MIME type
None registered; Linux desktops use text/x-c++src, and text/x-c is also common
Kind
Plain text (source code), compiled before it runs
Standard
ISO/IEC 14882, maintained by the ISO committee WG21; the current edition is ISO/IEC 14882:2024, known as C++23
First released
1985, by Bjarne Stroustrup at Bell Labs, who began the work in 1979; first ISO standard 1998
Compiled with
GCC (g++), Clang (clang++), Microsoft Visual C++ (cl)
Opens with
Any text editor or IDE: Visual Studio, VS Code, CLion, Xcode, Qt Creator
Comments
// line and /* block */
Magic number
None

The basics

What is a C++ file?

A .cpp file holds source code written in C++, a compiled language that Bjarne Stroustrup started at Bell Labs in 1979 as an extension of C. It is used where speed and control over memory matter: web browsers, game engines such as Unreal Engine, databases, trading systems, embedded devices and much desktop software.

The file is plain text, so you can read it in any text editor. To run it, a compiler translates it into machine code for one processor and operating system, then a linker joins the result with other compiled files and libraries into an executable program.

Three things that clear up common confusion:

  • .cpp, .cc and .cxx are the same thing. They are all C++ source files; projects simply pick one convention. The C++ standard doesn't mention file extensions at all.
  • Source files and headers have different jobs. A .cpp file is compiled; a header (.h or .hpp) holds declarations that several .cpp files include.
  • C++ is not C. It started as "C with classes" and can compile most C code, but it is a separate language with its own standard, its own keywords and a much larger standard library.

Anatomy

What's inside a C++ file

A C++ file is made of declarations: includes, namespaces, classes and functions, one of which is main. Here is a short program that greets each name given on the command line, part by part.

greet.cpp
// greet.cpp: greet everyone named on the command line
#include <iostream>
#include <string>
#include <utility>
#include <vector>

namespace app {

class Greeter {
public:
    explicit Greeter(std::string greeting) : greeting_{std::move(greeting)} {}

    std::string greet(const std::string& name) const
    {
        return greeting_ + ", " + name + "!";
    }

private:
    std::string greeting_;
};

}  // namespace app

int main(int argc, char* argv[])
{
    std::vector<std::string> names(argv + 1, argv + argc);
    if (names.empty()) {
        names.push_back("world");
    }

    const app::Greeter greeter{"Hello"};
    for (const auto& name : names) {
        std::cout << greeter.greet(name) << '\n';
    }
}
  1. 1// greet.cpp: …

    A comment

    // runs to the end of the line; /* … */ can span several lines.

  2. 2#include <iostream>

    Standard library headers

    C++'s own headers have no extension. Each one makes part of the standard library available: iostream for console output, string, vector, and utility for std::move.

  3. 3namespace app { … }

    A namespace

    Keeps names apart: this class is app::Greeter, so it can't clash with a Greeter in a library. Everything in the standard library lives in std.

  4. 4class Greeter { public: … private: … };

    A class

    Data and the functions that work on it, in one type. private members can only be used by the class itself. Note the semicolon after the closing brace.

  5. 5explicit Greeter(std::string greeting) : greeting_{…} {}

    A constructor

    Runs when an object is created. The member initialiser list after the colon sets greeting_, and std::move hands over the string's memory instead of copying it.

  6. 6std::string greet(const std::string& name) const

    A member function

    const std::string& passes the name by reference, without copying it. The const at the end promises not to change the object.

  7. 7int main(int argc, char* argv[])

    The entry point

    Every program starts in main. argc counts the command-line arguments and argv holds them; argv[0] is the program's own name.

  8. 8std::vector<std::string> names(argv + 1, argv + argc);

    A container from a template

    std::vector is a resizable array; <std::string> says what it holds. It frees its own memory when it goes out of scope, so there's no delete anywhere.

  9. 9for (const auto& name : names)

    A range-based for loop

    Visits each element. auto lets the compiler work out the type, and const auto& avoids copying each string.

  10. 10std::cout << … << '\n';

    Console output

    << sends values to the standard output stream in turn. '\n' ends the line; std::endl would also flush the stream, which is slower.

  11. 11}

    No return statement

    main is the one function that may end without return: reaching the end means return 0, success.

Under the hood

How to compile and run a C++ file

Each .cpp file is compiled on its own into an object file, and the linker combines the object files and libraries into one program. For a single file, one command does both:

SystemGet a compilerCompile and run
Linuxg++ or clang++ from the package manager, for example sudo apt install build-essentialg++ -std=c++20 -Wall -Wextra greet.cpp -o greet then ./greet
macOSApple's Clang, with xcode-select --install or Xcodeclang++ -std=c++20 -Wall greet.cpp -o greet then ./greet
Windows (Microsoft)Visual Studio or the Build Tools for Visual Studio, with the C++ workloadIn a Developer Command Prompt: cl /EHsc /W4 /std:c++20 greet.cpp then greet.exe
Windows (GCC)MinGW-w64, for example through MSYS2, or g++ inside WSLg++ -std=c++20 greet.cpp -o greet.exe then greet.exe
  • Use g++ or clang++, not gcc or clang. The C drivers compile a .cpp file as C++ but don't link the C++ standard library, so the build fails with errors like undefined reference to std::cout.
  • Say which standard you want. GCC 16 and later default to C++20 (-std=gnu++20), earlier versions from GCC 11 to C++17. Microsoft's compiler defaults to C++14 (/std:c++14), and offers /std:c++17, /std:c++20, /std:c++23preview and /std:c++latest.
  • On MSVC, add /EHsc. It turns on standard C++ exception handling; without it the compiler warns as soon as the code uses exceptions, which includes most of the standard library.

Beyond a few files, projects describe their build once in a build system and let it run the compiler. CMake is widely used for C++: it generates Makefiles, Ninja files or Visual Studio solutions from one description.

CMakeLists.txt
# CMakeLists.txt: describes the build once, for every compiler and IDE
cmake_minimum_required(VERSION 3.20)
project(report LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(report main.cpp stats.cpp)

# then, in a terminal:
#   cmake -S . -B build
#   cmake --build build

Conventions

.cpp vs .cc vs .cxx, and the other C++ extensions

Compilers choose the language from the extension. GCC documents .cc, .cp, .cxx, .cpp, .CPP, .c++ and .C as C++ source, and .hh, .hpp, .hxx, .h++ and .H as C++ headers. Pick one pair and keep it across a project.

ExtensionWhat it isNotes
.cppC++ sourceThe most common choice, and Visual Studio's default
.ccC++ sourceUsed by many Unix projects and by Google's C++ style
.cxx, .c++C++ sourceLess common; .c++ contains characters some tools dislike in file names
.CC++ sourceOnly on case-sensitive systems. On Windows and macOS, .C and .c are the same name, so avoid it
.hpp, .hh, .hC++ header.h is also C's extension, so .hpp makes it clear a header needs C++
.ipp, .tpp, .inlTemplate or inline codeA convention, not a standard: implementation details included at the end of a header
.cppm, .ixxModule interfaceC++20 modules: Clang recommends .cppm, Visual Studio uses .ixx
  • Encoding: save source as UTF-8. Microsoft's compiler reads a file without a byte order mark in the system's code page unless you pass /utf-8, so either add the flag (best) or save with a BOM. GCC and Clang read UTF-8 by default and accept a BOM.
  • Line endings: LF and CRLF both compile. Mixed or converted line endings show up in diffs, not in builds.

Versions

C++ standards: C++98 to C++26

C++ is defined by ISO/IEC 14882, revised every three years since 2011. A .cpp file doesn't record which version it targets; you choose one with -std=c++20 or /std:c++20. The macro __cplusplus reports it (MSVC needs /Zc:__cplusplus to set it correctly, or use _MSVC_LANG).

NamePublishedNotable for
C++98, C++031998, 2003The first ISO standard and its corrections: templates, the standard library's containers and algorithms
C++112011The big modernisation: auto, lambdas, move semantics, smart pointers, range-based for, threads
C++142014Smaller: generic lambdas, std::make_unique
C++172017Structured bindings, std::optional, std::string_view, std::filesystem, if constexpr
C++202020Concepts, ranges, coroutines, modules, std::format, the <=> operator
C++23October 2024, as ISO/IEC 14882:2024std::print, std::expected, import std, deducing this
C++26Not yet publishedFinished by the committee in March 2026 and going through ISO's approval process. Adds reflection, contracts and std::execution

Why C++23 says 2024: its technical work was finished in February 2023, but ISO's publication process took until October 2024. Compiler support always trails the standard and differs by feature, so check your compiler's status page before relying on something new.

C++20

Modules: .cppm and .ixx files

Since C++20 a library can be a module instead of a header. A module interface file starts with export module name; and marks what it shares with export; other files write import name; instead of #include. Modules are compiled once instead of being re-read by every file that uses them, and macros and private helpers don't leak out.

  • Extensions aren't standardised. Clang recommends .cppm (or .ccm, .cxxm, .c++m); Visual Studio uses .ixx by default; GCC accepts any name with -x c++.
  • Build order matters. A module must be compiled before the files that import it, so plain g++ *.cpp style builds don't work. CMake 3.28 and later handle this; by hand you compile the interface first, as in the sample files below.
  • import std; brings in the whole standard library at once in C++23. Visual Studio 2022 supports it from version 17.5; with Clang and GCC it depends on the version and build setup.

Troubleshooting

C++ build errors people hit most, and what they mean

MessageUsual causeFix
undefined reference to std::cout (or other std:: names)Built with gcc instead of g++, so the C++ library wasn't linkedUse g++ or clang++
'cout' was not declared in this scope / 'string' is not a member of 'std'A missing #include, or std:: left off. Code that relied on one header pulling in another breaks when compilers tidy their headers, as GCC 15 didInclude the header for every standard name you use
undefined reference to 'f()' (MSVC: LNK2019 unresolved external symbol)A linker error: something was declared but its definition wasn't compiled inAdd the missing .cpp file or library to the build
multiple definition of 'f()' (MSVC: LNK2005)A function or variable defined in a header included by several .cpp filesMark it inline, or move the definition into one .cpp file
'ranges' is not a member of 'std', 'concept' does not name a type…Newer code compiled in an older standard modeAdd -std=c++20 (or the version the code needs)
no matching function for call to …Argument types don't fit any overload; with templates the message can run to dozens of linesRead the first error and the "candidate" notes; fix the types at the call
warning C4530: C++ exception handler used, but unwind semantics are not enabledMSVC without /EHscAdd /EHsc

Compiling isn't proof it works

Like C, C++ has undefined behaviour: reading past the end of an array, using an object after it's destroyed or a data race between threads compiles fine and then fails unpredictably. Build with warnings on and test with -fsanitize=address,undefined in GCC or Clang.

How to

How to open and edit a C++ file

  • Read it: any text editor shows it, and so does a browser, as plain text.
  • Edit it: Visual Studio (Windows), VS Code with Microsoft's C/C++ extension or clangd, CLion, Xcode (macOS) and Qt Creator are the usual choices. They need to know your build settings (include paths, standard) to show errors correctly; CMake can export them as compile_commands.json.
  • Format and check it: clang-format applies a consistent style; clang-tidy and compiler warnings catch likely bugs.
  • Try it online: Compiler Explorer compiles snippets with many compiler versions in the browser and shows the generated assembly.

Security

Is it safe to open a C++ file?

Opening a .cpp file in an editor is safe: it's text, and nothing runs. Building and running it is another matter:

  • Builds run code. CMake scripts, Makefiles and package managers such as vcpkg and Conan run commands on your computer while building. Read a downloaded project's build files first, or build it in a container.
  • The program runs with your permissions. A compiled program can do anything your user account can.
  • Memory safety is up to the programmer. C++ inherits C's unchecked pointers and arrays, the cause of many security vulnerabilities. Modern C++ reduces the risk with containers, smart pointers and std::span instead of raw pointers, and C++26 adds a hardened standard library that checks bounds.

Free downloads

Sample C++ files to download

Free sample C++ files for testing compilers, IDEs, syntax highlighting, code viewers and upload filters. Each one compiles with GCC and Clang using -Wall -Wextra -pedantic -std=c++20 without a single warning, and runs.

sample-program.cpp · 4.5 KBDownloadOpen
Loading…

What's inside sample-program.cpp

The file is commented: open it in a text editor and each numbered comment marks one of these parts. Compile it with c++ -std=c++20 sample-program.cpp -o sample-program and run it to see a stock report.

  1. Comments 1 and 2: includes and a namespace

    Thirteen standard library headers, and a shop namespace around the program's own names.

  2. Comment 3: a class

    shop::Item with private members, a constructor that throws std::invalid_argument for negative stock, and const accessor functions.

  3. Comments 4 and 5: a constrained template and std::optional

    A function template limited to floating-point types with the C++20 concept std::floating_point, and a search function that returns std::optional instead of a null pointer.

  4. Comments 6 and 7: a vector and an algorithm

    A std::vector of items that manages its own memory, sorted with std::ranges::sort and a projection, largest value first.

  5. Comments 8 and 9: output, a lambda and a map

    Aligned columns with <iomanip>, then a lambda that classifies stock levels and a std::map that counts them, read back with structured bindings.

  6. Comments 10 to 12: optional, exceptions and the exit status

    Testing an optional before using it, a try/catch that handles the constructor's exception, and return 0.

All sample C++ files

  • Commented sample program

    sample-program.cpp · 4.5 KB (4,583 bytes)

    A complete C++20 program that prints a sorted stock report: a class, a namespace, a concept-constrained template, std::optional, std::vector, ranges, a lambda, std::map and exceptions, with numbered comments explaining each part.

    • Checking compilers, IDEs and syntax highlighters on modern C++
    • Teaching the parts of a C++ program
  • Hello world

    sample-hello.cpp · 305 bytes

    The classic first C++ program, with build commands for GCC, Clang and MSVC in its comments.

    • A minimal compile test
    • Checking a new toolchain works
  • UTF-8 with a byte order mark

    sample-utf8-bom.cpp · 1.9 KB (1,911 bytes)

    Saved as UTF-8 with a BOM (the bytes EF BB BF first), so Microsoft's compiler reads it correctly even without /utf-8. Prints greetings in seven scripts, plus emoji, with their size in bytes and code points, and shows why C++20's u8"…" literals can't go straight to std::cout.

    • Testing how editors, diffs and tools handle a BOM
    • Source-encoding tests across GCC, Clang and MSVC
  • C++20 module interface

    sample-module.cppm · 1.4 KB (1,421 bytes)

    A module named greetings with a global module fragment, exported and private functions, and an exported constant. Its comments give the build commands for GCC and Clang, tested with both.

    • Testing tools and build systems on C++20 modules
    • Checking that a viewer or filter recognises the `.cppm` extension
  • Program that imports the module

    sample-module-main.cpp · 408 bytes

    import greetings; next to a classic #include. Build it together with sample-module.cppm, which must be compiled first.

    • Module build-order tests
    • A minimal `import` example
  • 100 KB C++ file

    sample-100kb.cpp · 100 KB (102,400 bytes)

    A constexpr std::array of the first 13,300 prime numbers and a program that checks them with std::ranges algorithms, padded with a comment to exactly 102,400 bytes.

    • Upload and size-limit tests
    • Editor, highlighter and compile-time benchmarks

Ways to test with them

  • Standard mode: sample-program.cpp needs C++20 (concepts and ranges). Compile it with -std=c++17 to see what an older standard mode reports.
  • Encoding and BOM: run sample-utf8-bom.cpp through your editor, formatter and Git; check the first three bytes survive, and compile it with MSVC with and without /utf-8.
  • Modules: build sample-module.cppm and sample-module-main.cpp with your build system to check it orders module builds correctly.
  • Upload limits: sample-100kb.cpp is exactly 102,400 bytes, for testing a limit at the boundary.

Free to use for testing, teaching and demos, commercially or not, with no attribution needed. A link back to this page is always appreciated.

Put it online

Have a C++ file? Give it a link.

Drop a .cpp file on 99helpers and it gets its own web address. Anyone who opens the link reads the code as plain text in their browser: it is never compiled or run, which makes it a simple way to share code for review, teaching or a bug report.

Questions

C++ files, frequently asked

What is a .cpp file?

A source code file written in C++. It's plain text that a compiler such as g++, clang++ or Microsoft's cl turns into a program.

How do I open a CPP file?

Open it in a text editor or an IDE such as Visual Studio, VS Code, CLion or Xcode. To run the code, compile it first.

How do I run a .cpp file?

Compile it, then run the program it produces. On Linux or macOS: g++ -std=c++20 file.cpp -o file (or clang++), then ./file. On Windows with Visual Studio's tools: cl /EHsc file.cpp in a Developer Command Prompt, then file.exe.

What's the difference between .cpp, .cc and .cxx?

None in the content: all three are C++ source files. Projects choose one by convention; .cpp is the most common and .cc is popular on Unix and at Google.

What's the difference between .cpp and .h or .hpp?

A .cpp file is compiled into the program. A header (.h or .hpp) contains declarations, templates and inline functions that .cpp files #include; it isn't compiled on its own.

What's the latest C++ standard?

The latest published one is C++23, ISO/IEC 14882:2024, published in October 2024. C++26 was finished by the committee in March 2026 and is going through ISO's approval process, so it isn't an official standard yet.

Why do I get "undefined reference to std::cout"?

You compiled with gcc instead of g++. gcc compiles the file as C++ but doesn't link the C++ standard library. Use g++ or clang++.

Can a C++ compiler compile C code?

Usually, but not always. Most C is valid C++, but some isn't, such as assigning malloc's result without a cast or using C++ keywords like new as names. Compile C files as C and link them to C++ code with extern "C".

Related formats

Other file types explained

Keep going

Related

Sources

Last reviewed 27 October 2026.