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:
- Start with any document class:
\documentclass{article}
- Load the
listings
package:\usepackage{listings}
- Begin the document:
\begin{document}
- Start an
lstlisting
environment with an option for the language:\begin{lstlisting}[language = C++]
- Continue with the code you would like to print:
// include standard input/output stream objects: #include <iostream> // the main method: int main() { std::cout << ""Hello TeX world!"" << std::endl; }
- End the
lstlisting
environment and the document:\end{lstlisting} \end{document}
- Compile the document and have a look: