8
votes

Can anyone recommend me a good template to include C source code with line numbering in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:

(1)   /* Hello World program */
(2)
(3)   #include<stdio.h>
(4)
(5)   main()
(6)   {
(7)    printf("Hello World");
(8)   }

Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.

Thanks so much Richard

5
see tex.stackexchange.com also look at stackoverflow.com/questions/741985/…deinst
Probably better answer can be get on TeX and LaTeX stackexchange.Grzegorz Gierlik

5 Answers

15
votes

As others have said, the listings package will probably do what you want using something like the following:

\lstset{
  language=C,                % choose the language of the code
  numbers=left,                   % where to put the line-numbers
  stepnumber=1,                   % the step between two line-numbers.        
  numbersep=5pt,                  % how far the line-numbers are from the code
  backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
  showspaces=false,               % show spaces adding particular underscores
  showstringspaces=false,         % underline spaces within strings
  showtabs=false,                 % show tabs within strings adding particular underscores
  tabsize=2,                      % sets default tabsize to 2 spaces
  captionpos=b,                   % sets the caption-position to bottom
  breaklines=true,                % sets automatic line breaking
  breakatwhitespace=true,         % sets if automatic breaks should only happen at whitespace
  title=\lstname,                 % show the filename of files included with \lstinputlisting;
}

\lstinputlisting{HelloWorld.c}

A more powerful alternative would be to use the minted package, although this will do much more than what you're currently asking, as it uses/requires pygments to be installed on your system so that it can fully tokenize the code you give it.

10
votes

You might want to have a look at the listings package. It is very flexible and easy to use.

1
votes

Take a look at Code listings in LaTeX. You'll find a couple of alternatives there. Some options are:

0
votes

Use lgrind package for latex. It converts your code into a .tex file

-1
votes

CWEB had a nice C formatter.