Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Use fragile option for your frame and use listings package to include and format your code. –  Paul Gaborit Aug 21 '12 at 16:12
1  
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

3 Answers 3

up vote 5 down vote accepted

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.

share|improve this answer

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}
share|improve this answer

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.

share|improve this answer

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