# 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
% https://www.packtpub.com/hardware-and-creative/latex-cookbook
\documentclass[border=30pt]{standalone}
\usepackage{xcolor}
%\usepackage{inconsolata}% would give a nice typewriter font
\newcommand{\Cpp}{C\texttt{++}}
\usepackage{listings}
\lstset{
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,
float,
}
\begin{document}
\begin{lstlisting}
// include standard input/output stream objects:
#include
// the main method:
int main()
{
std::cout << "Hello TeX world!" << std::endl;
}
\end{lstlisting}
\end{document}
Click to download: listing.texlisting.pdf
Open in Overleaf: listing.tex