LOGBOOK

HELP

1 / 34
Other keys: showSpace: good1-4: rate0: skip5: flag6: invert

Question

How do you compile a C++ program from the command line?

Answer

Use the GNU C++ compiler g++: g++ hello.cpp produces a.out, or g++ -o hello hello.cpp to name the output.

C++ source files use the .cpp extension and are built with g++, the C++ front-end of the GNU Compiler Collection (the C front-end is gcc).

# Creates a.out
$ g++ hello.cpp
# Creates 'hello' executable
$ g++ -o hello hello.cpp
# Run it
$ ./hello

Key differences from C:

  • Use g++ instead of gcc (so the C++ standard library links automatically)
  • File extension is .cpp (not .c)

In a Makefile:

CXX=g++
CXXFLAGS=-Wall -O2 -std=c++0x

Tip: CXX is the conventional Makefile variable for the C++ compiler (mirroring CC for C), and CXXFLAGS holds its flags. -std= picks the language standard. c++0x was the working name for what became C++11; modern code uses concrete names like c++17 or c++20.

or press any other key