Code listings in LaTeX

'Pretty' code listings are sometimes considered worthwhile by the "ordinary" programmer, but they have a serious place in the typesetting of dissertations by computer science and other students who are expected to write programs. Simple verbatim listings of programs are commonly useful, as well.

Verbatim listings are dealt with elsewhere, as is the problem of typesetting algorithm specifications.

The listings package is widely regarded as the best bet for formatted output (it is capable of parsing program source, within the package itself), but there are several well-established packages that rely on a pre-compiler of some sort. You may use listings to typeset snippets that you include within your source:

\usepackage{listings}
\lstset{language=C}
...
\begin{document}
\begin{lstlisting}
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{lstlisting}
\end{document}
or you can have it typeset whole files:
\usepackage{listings}
\lstset{language=C}
...
\begin{document}
\lstinputlisting{main.c}
\end{document}
These very simple examples may be decorated in a huge variety of ways, and of course, there are other languages in the package's vocabulary than just C...

Highlight is attractive if you need more than one output format for your program: as well as (La)TeX output, highlight will produce (X)HTML, RTF and XSL-FO representations of your program listing. Documentation is available on the highlight project site.

The lgrind system is another well-established pre-compiler, with all the facilities one might need and a wide repertoire of languages.

The tiny_c2l system is more recent: users are encouraged to generate their own driver files for languages it doesn't already deal with.

The venerable c2latex is extremely simple; it makes no attempt to prettify the source itself, and relies (for example) on the author's indentation style. It's distributed as pretty clean C source (which is probably not a problem for someone who has C source to typeset).

The C++2LaTeX system comes with strong recommendations for use with C and C++.

c2latex
support/c2latex (zip, browse)
C++2LaTeX
support/C++2LaTeX-1_1pl1 (zip, browse)
highlight
support/highlight (zip, browse)
lgrind
nonfree/support/lgrind (zip, browse)
listings.sty
macros/latex/contrib/listings (zip, browse)
tiny_c2l
support/tiny_c2l (zip, browse)

This question on the Web: http://www.tex.ac.uk/cgi-bin/texfaq2html?label=codelist