14

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?

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

3 Answers 3

11

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.

12

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.