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
It is possible to pull the source code in LaTeX from a file using the command \lstinputlisting[language=LANGUAGENAME]{FILE NAME}. This command also lets you choose which language the code will be in.
LaTeX is a programming language in a fashion similar to C. In particular, LaTeX code must be compiled to produce a document. This is often done using pdflatex , a program which produces a PDF file from a LaTeX document.
Referencing Code Listings\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++]{code_sample. cpp} An example table can be seen in \ref{lst:listing-cpp}. Also note how the "Listing" prefix is automatically added within the document text whenever the reference is called.
Source Listings means the human-readable instructions together with annotations thereto which comprise the source code of the COMPUTER PROGRAM.
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.
You might want to have a look at the listings
package. It is very flexible and easy to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With