Source code in LaTeX
I’m about to hand in my Bachelor’s Thesis, and needed to include some source code in the report. Previously, I’ve used the following macro in the preamble:
\usepackage{moreverb}
\def\sourcetabsize{4}
\newenvironment{sourcestyle}{\begin{scriptsize}}{\end{scriptsize}}
\def\sourceinput#1{\par\begin{sourcestyle}\verbatimtabinput[\sourcetabsize]{#1}\end{sourcestyle}\par}
And then included the source files using:
\begin{figure}[h]
\sourceinput{helloworld.c}
\caption{hello world c code}
\end{figure}
This has some drawbacks, namely:
- The appearence is sort of restriced, unless you want to manually rewrite the macro (which quickly grows out of hand)
- Source code is limited to one page (unless you include them without the figure)
- This seems a bit like a hack
After some googling, I found out that there is actually a package called listings, which does this in a more proper way
This should go in the preamble:
\usepackage{listings}
\lstset{tabsize=2,breaklines=true,breakatwhitespace=true,basicstyle=\scriptsize\tt,morecomment=[l]{//},
postbreak=\mbox{{\tiny$\hookrightarrow$}}}
More options for lstset are available in the pdf, or at this blog.
To include a source code file, type this anywhere you want it included:
\subsection*{hello world c code}
\lstinputlisting{helloworld.c}
So, don’t put stuff in figures, unless you really need to! Now I will just have to rewrite my references to my late figures…