# How do I add syntax coloring to my C++ source code in beamer

I have just learned how to insert source code into beamer with the listings package. However I dont know how to go about adding any syntax coloring on the C++ source code.

How do I do that?

Here is the code I am currently using for source code insertion.

\documentclass{beamer}
\setbeamercovered{transparent}
%\usepackage{pxfonts}
\usepackage{listings}

\begin{document}

\begin{frame}[fragile]
\frametitle{Inserting source code}
\lstset{language=C++}
\begin{lstlisting}
#include<stdio.h>
#include<iostream>
int main(void)
{
printf("Hello World\n");
return 0;
}
\end{lstlisting}
\end{frame}
\end{document}

-

This is an example with C++ code highlighted; the two frames show the difference between adopting the typewriter font and not:

\documentclass{beamer}
\setbeamercovered{transparent}
\usepackage{listings}

\begin{document}

% Using typewriter font: \ttfamily inside \lstset
\begin{frame}[fragile]
\frametitle{Inserting source code}
\lstset{language=C++,
basicstyle=\ttfamily,
keywordstyle=\color{blue}\ttfamily,
stringstyle=\color{red}\ttfamily,
morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
#include<stdio.h>
#include<iostream>
// A comment
int main(void)
{
printf("Hello World\n");
return 0;
}
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{Inserting source code without setting typewriter}
\lstset{language=C++,
keywordstyle=\color{blue},
stringstyle=\color{red},
morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
#include<stdio.h>
#include<iostream>
// A comment
int main(void)
{
printf("Hello World\n");
return 0;
}
\end{lstlisting}
\end{frame}
\end{document}


Notice that there's no difference from Beamer or standard document in using listings. The package guide explains in detail how to do this, but you can also find information looking at the apposite tag listing on this site. The command \ttfamily sets the given style in typewriter.

-
Thank you. One question. Could you explain what this "ttfamily " is? Is it a specific font? –  smilingbuddha Aug 21 '12 at 16:45
Yes, it's the typewriter font. –  Juri Robl Aug 21 '12 at 16:56