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 ofgcc(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.
Note saved — thanks!
Question
How do you write "Hello, world!" in C++?
Answer
Include <iostream>, then write cout << "Hello, world!" << endl; inside main().
#include <iostream>
using namespace std;
int main(void) {
cout << "Hello, world!" << endl;
return 0;
}
Key C++ elements:
#include <iostream>— C++ stream I/O library (not C'sstdio.h)using namespace std;— lets you writecoutinstead ofstd::coutcout <<— sends text to the output stream (the C++ replacement forprintf)endl— writes a newline and flushes the buffer (or use"\n"for just the newline)
Compile and run:
$ g++ -o hello hello.cpp
$ ./hello
Hello, world!
Note saved — thanks!