15

Possible Duplicate:
How display LaTeX code in LaTeX document?
How do I fit java style source code in one frame in beamer?

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

3 Answers3

13

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}
12

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.

Juri Robl
  • 4,763
1

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.

G. Poore
  • 12,417