Printing a code listing

Documentation may contain code samples. The same applies to theses in computer science. While pseudocode of algorithms was covered in the previous recipe, we now like to typeset real code. To save space, we will use a small "hello world" program as an example.

How to do it...

We will use the listings package, which has been designed for that purpose. Follow these steps:

  1. Start with any document class:
    \documentclass{article}
  2. Load the listings package:
    \usepackage{listings}
  3. Begin the document:
    \begin{document}
  4. Start an lstlisting environment with an option for the language:
    \begin{lstlisting}[language = C++]
  5. Continue with the code you would like to print:
    // include standard input/output stream objects: #include <iostream> // the main ...

Get LaTeX Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.