Example: Printing a code listing

Published 2015-09-25 | Author: Stefan Kottwitz

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.

Download as: [PDF] [TEX]  •  [Open in Overleaf]

Printing a code listing
% 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 <iostream>
// the main method:
int main()
{
    std::cout << "Hello TeX world!" << std::endl;
}
\end{lstlisting}
\end{document}

Comments

Adding comments is currently not enabled.

There are currently 0 comments on this entry.

Features
Tags
Scientific and technical areas
LaTeX Cookbook

Cookbook

LaTeX Beginners Guide

Creative Commons License