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,.ccand.cxxare 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
.cppfile is compiled; a header (.hor.hpp) holds declarations that several.cppfiles 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 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
// greet.cpp: …A comment
//runs to the end of the line;/* … */can span several lines. - 2
#include <iostream>Standard library headers
C++'s own headers have no extension. Each one makes part of the standard library available:
iostreamfor console output,string,vector, andutilityforstd::move. - 3
namespace app { … }A namespace
Keeps names apart: this class is
app::Greeter, so it can't clash with aGreeterin a library. Everything in the standard library lives instd. - 4
class Greeter { public: … private: … };A class
Data and the functions that work on it, in one type.
privatemembers can only be used by the class itself. Note the semicolon after the closing brace. - 5
explicit Greeter(std::string greeting) : greeting_{…} {}A constructor
Runs when an object is created. The member initialiser list after the colon sets
greeting_, andstd::movehands over the string's memory instead of copying it. - 6
std::string greet(const std::string& name) constA member function
const std::string&passes the name by reference, without copying it. Theconstat the end promises not to change the object. - 7
int main(int argc, char* argv[])The entry point
Every program starts in
main.argccounts the command-line arguments andargvholds them;argv[0]is the program's own name. - 8
std::vector<std::string> names(argv + 1, argv + argc);A container from a template
std::vectoris a resizable array;<std::string>says what it holds. It frees its own memory when it goes out of scope, so there's nodeleteanywhere. - 9
for (const auto& name : names)A range-based for loop
Visits each element.
autolets the compiler work out the type, andconst auto&avoids copying each string. - 10
std::cout << … << '\n';Console output
<<sends values to the standard output stream in turn.'\n'ends the line;std::endlwould also flush the stream, which is slower. - 11
}No return statement
mainis the one function that may end withoutreturn: reaching the end meansreturn 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:
| System | Get a compiler | Compile and run |
|---|---|---|
| Linux | g++ or clang++ from the package manager, for example sudo apt install build-essential | g++ -std=c++20 -Wall -Wextra greet.cpp -o greet then ./greet |
| macOS | Apple's Clang, with xcode-select --install or Xcode | clang++ -std=c++20 -Wall greet.cpp -o greet then ./greet |
| Windows (Microsoft) | Visual Studio or the Build Tools for Visual Studio, with the C++ workload | In 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 WSL | g++ -std=c++20 greet.cpp -o greet.exe then greet.exe |
- Use
g++orclang++, notgccorclang. The C drivers compile a.cppfile as C++ but don't link the C++ standard library, so the build fails with errors likeundefined 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++23previewand/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: 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 buildConventions
.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.
| Extension | What it is | Notes |
|---|---|---|
.cpp | C++ source | The most common choice, and Visual Studio's default |
.cc | C++ source | Used by many Unix projects and by Google's C++ style |
.cxx, .c++ | C++ source | Less common; .c++ contains characters some tools dislike in file names |
.C | C++ source | Only on case-sensitive systems. On Windows and macOS, .C and .c are the same name, so avoid it |
.hpp, .hh, .h | C++ header | .h is also C's extension, so .hpp makes it clear a header needs C++ |
.ipp, .tpp, .inl | Template or inline code | A convention, not a standard: implementation details included at the end of a header |
.cppm, .ixx | Module interface | C++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).
| Name | Published | Notable for |
|---|---|---|
| C++98, C++03 | 1998, 2003 | The first ISO standard and its corrections: templates, the standard library's containers and algorithms |
| C++11 | 2011 | The big modernisation: auto, lambdas, move semantics, smart pointers, range-based for, threads |
| C++14 | 2014 | Smaller: generic lambdas, std::make_unique |
| C++17 | 2017 | Structured bindings, std::optional, std::string_view, std::filesystem, if constexpr |
| C++20 | 2020 | Concepts, ranges, coroutines, modules, std::format, the <=> operator |
| C++23 | October 2024, as ISO/IEC 14882:2024 | std::print, std::expected, import std, deducing this |
| C++26 | Not yet published | Finished 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.ixxby 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++ *.cppstyle 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
| Message | Usual cause | Fix |
|---|---|---|
undefined reference to std::cout (or other std:: names) | Built with gcc instead of g++, so the C++ library wasn't linked | Use 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 did | Include 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 in | Add 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 files | Mark 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 mode | Add -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 lines | Read the first error and the "candidate" notes; fix the types at the call |
| warning C4530: C++ exception handler used, but unwind semantics are not enabled | MSVC without /EHsc | Add /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-formatapplies a consistent style;clang-tidyand 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::spaninstead 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.
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.
Comments 1 and 2: includes and a namespace
Thirteen standard library headers, and a
shopnamespace around the program's own names.Comment 3: a class
shop::Itemwith private members, a constructor that throwsstd::invalid_argumentfor negative stock, andconstaccessor functions.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 returnsstd::optionalinstead of a null pointer.Comments 6 and 7: a vector and an algorithm
A
std::vectorof items that manages its own memory, sorted withstd::ranges::sortand a projection, largest value first.Comments 8 and 9: output, a lambda and a map
Aligned columns with
<iomanip>, then a lambda that classifies stock levels and astd::mapthat counts them, read back with structured bindings.Comments 10 to 12: optional, exceptions and the exit status
Testing an optional before using it, a
try/catchthat handles the constructor's exception, andreturn 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::mapand 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 BFfirst), 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'su8"…"literals can't go straight tostd::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
greetingswith 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 withsample-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::arrayof the first 13,300 prime numbers and a program that checks them withstd::rangesalgorithms, 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.cppneeds C++20 (concepts and ranges). Compile it with-std=c++17to see what an older standard mode reports. - Encoding and BOM: run
sample-utf8-bom.cppthrough 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.cppmandsample-module-main.cppwith your build system to check it orders module builds correctly. - Upload limits:
sample-100kb.cppis 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
- isocpp.org: The C++ Standard
- Herb Sutter: C++26 is done! Trip report, March 2026
- GCC 16.1 release announcement (C++20 by default)
- Microsoft Learn: /std (Specify language standard version)
- Clang: Standard C++ Modules
- Microsoft Learn: /utf-8 (source and execution character sets)
Last reviewed 27 October 2026.