C++ Cheat Sheet
The compiler commands you'll reach for constantly — before any of the language concepts.
Beginner
g++ (GCC) in the examples, but the flags are the same
shape for clang++. Every command below assumes a single file called
main.cpp in the current directory.
g++ -X c++ a.cppp -o main for compiling a file with
a non-standard extension — two typos in one line. The real flag is lowercase
-x, and it goes before the file it applies to:
static_assert runs at compile time, not runtime — if the condition is
false, the build fails with your message instead of the program misbehaving later.
static_assert(sizeof(int) == 4, "this code assumes a 32-bit int");
template <typename T>
struct only_for_small_types {
static_assert(sizeof(T) <= 8, "T is too large for this container");
};
namespace geometry {
double area(double r) { return 3.14159 * r * r; }
}
namespace physics {
double area(double base, double height) { return base * height; } // no collision with geometry::area
}
geometry::area(2.0);
using namespace physics; // avoid this in headers — it defeats the point of the namespace
area(3.0, 4.0);
CXX = g++
CXXFLAGS = -Wall -Wextra -std=c++17 -O2
TARGET = main
SRCS = $(wildcard *.cpp)
$(TARGET): $(SRCS)
$(CXX) $(CXXFLAGS) -o $(TARGET) $(SRCS)
clean:
rm -f $(TARGET)