Introduction
A .cpp file holds source code in C++, the language that grew out of
C with classes, templates and a large standard library.
As in C, a compiler turns each source file into an object file, and a linker joins them
into a program or library.
Compilers do not agree on one extension, so several are common: .cpp,
.cc and .cxx for source files, and .hpp,
.hh, .hxx or plain .h for headers. Since C++20,
modules may use extensions such as .cppm or .ixx, depending on
the compiler.
Structure
A C++ source file is plain text with no header or signature. Like C, it first passes
through the preprocessor, which handles #include, #define and
#if lines. What remains is a series of declarations: namespaces, classes,
templates, functions and variables. Headers hold the declarations that several source
files share; templates are usually defined in full in headers, because the compiler
needs their code wherever they are used.
#include <iostream>
#include <string>
int main()
{
std::string name = "world";
std::cout << "Hello, " << name << '\n';
}
Links
Software
- GCC (Linux, Windows, macOS)
- Clang (Linux, Windows, macOS)
- Visual Studio (Windows)
- CLion (Windows, macOS, Linux)
- Xcode (macOS)
- Visual Studio Code (Windows, macOS, Linux)
Developers
- libclang, C interface to Clang’s parser, with Python bindings
- tree-sitter-cpp, C++ grammar for the Tree-sitter parser used by editors
Reference
- ISO/IEC JTC1/SC22/WG21, the committee that maintains the C++ standard, with its working papers
- C++ reference at cppreference.com