Include Computer Code in a LaTeX Document

This document describes techniques for include computer code, e.g. C or MATLAB, into a LaTeX document.

Direct Coding

Computer code is usually typeset in monospaced font. A quick way to include a block of code is to use a verbatim environment. Here is the classic Hello, world! program in C:

\documentclass{article}

\begin{document}

\begin{verbatim}
#include<stdio.h>

main()
{
    printf("Hello, world!\n");
}
\end{verbatim}
\end{document}

A more flexible technique is to use the alltt environment from the alltt package. The alltt allows you to embed commands in the code source, but that also raises complications because any \ characters are interpreted as the start of a command. So, to use alltt to typeset Hello, world!, the newline \n has to be replaced with \textbackslash{n}

\documentclass{article}
\usepackage{alltt}    %  in the preamble

\begin{document}

\begin{alltt}
#include<stdio.h>

main()
{
    printf("Hello, world!\textbackslash{n}");
}
\end{alltt}
\end{document}

Note that {n} is used to suppress the space between \textbackslash and n, i.e. n is not an argument of the \textbackslash command.

Using the matlab package

I've written the matlab package for including code in LaTeX documents. The matlab package includes an mtext environment for code blocks, VerbListing, VerbListingBoxed, VerbListingNumber commands for including source code from external files, and the Listing environment to include code in a float environment.

The matlab package just provides some wrapper environments for commands from the float and fancyvrb packages.

Some day I'll provide more HTML documentation here. In the meantime you can view the documentation in PDF, look at the matlab.sty source code, or download a zip archive of the documentation and sample code.