Printing a code listing

Documentation may contain code samples. The same applies to theses in computer science. While pseudo-code of algorithms was covered in the another example, we now like to typeset real code. To save space, we will use a small “hello world” program as example.

We will use the listings package which has been designed for that purpose.

The code is fully explained in the LaTeX Cookbook, Chapter 11, Science and Technology, Printing a code listing.

Edit and compile if you like:
% Printing a code listing
% Author: Stefan Kottwitz
%\usepackage{inconsolata}% would give a nice typewriter font
  language     = C++,
  basicstyle   = \ttfamily,
  keywordstyle = \color{blue}\textbf,
  commentstyle = \color{gray},
  stringstyle  = \color{green!70!black},
  stringstyle  = \color{red},
  columns      = fullflexible,
  numbers      = left,
  numberstyle  = \scriptsize\sffamily\color{gray},
  caption      = A hello world program in \Cpp,
  showstringspaces = false,
// include standard input/output stream objects:
// the main method:
int main()
    std::cout << "Hello TeX world!" << std::endl;
Click to download: listing.texlisting.pdf
Open in Overleaf: listing.tex