# How to put C++ source code into beamer slides [duplicate]

How do I add C++ formatted and coloured source code to my beamer presentations? Any simple ways to do this?

-

## marked as duplicate by Thorsten, Gonzalo Medina, Werner, Harish Kumar, percusseAug 22 '12 at 3:39

Use fragile option for your frame and use listings package to include and format your code. –  Paul Gaborit Aug 21 '12 at 16:12
I suggest two answers as reference: this one and this one (referred to Java, but it's the same). –  Claudio Fiandrino Aug 21 '12 at 16:15

Use the package listings or minted. Listings is easier to install, as minted needs python, it uses pygments, but often produces nicer results. Also you need to use the fragile option on your frame, so the content of the frame gets writen to an external file and can be properly processed. This slows the compiling down, so don't use the option where you don't need to!

But remember that the space on the beamer frames is very limited, so you can't (and really shouldn't) get very much code on one page.

-

You can define the verbatim part before the frame environment then you do not need the fragile option.

\documentclass{beamer}
\usepackage{listings}

\begin{document}

\defverbatim[colored]\lstI{
\begin{lstlisting}[language=C++,basicstyle=\ttfamily,keywordstyle=\color{red}]
int main() {
// Define variables at the beginning
// of the block, as in C:
CStash intStash, stringStash;
int i;
char* cp;
ifstream in;
string line;
[...]
\end{lstlisting}
}

\begin{frame}{A Listings Demo}{C++}
\lstI
\end{frame}

\end{document}

-

Another option is PythonTeX, specifically the \pygment command and the pygments environment. Like minted, PythonTeX requires Python and Pygments. The highlighted results are saved, so you only need to run Python when you have modified the code that needs highlighting. Unicode is supported.

You will need to use the fragile option for the beamer frames.

-