Try   HackMD

Using LaTeX to create code snippets

Introduction

In this tutorial, I will explain how to create code snippets, regardless of your knowledge of LaTeX. If you're in a rush, or you don't feel like reading all this, you can always skip down to the bottom and copy the final result.

LaTeX editor

There are a few LaTeX IDEs available, however they are rather complicated, and are overengineered for the task at hand. Instead of using a standard IDE, I highly recommend using Overleaf instead, an online LaTeX editor. You do not need to install anything, everything is contained on the website. If, however, you do know how to use a certain LaTeX IDE, then go ahead.

Setting up Overleaf

Using Overleaf is a rather straightforward process, you sign up/login to an account, click on
"New Project", then click on "Blank Project". Give it a name, and you're good to go. The automatically generated code in the file can be deleted.

Getting started

Once you've set up your LaTeX environment in Overleaf, or your IDE of choice, start off by adding this line at the top of your main.tex file:

\documentclass[a4paper]{article}

This line essentially defines the type of document your LaTeX project will be. This is the standard.

Required packages

Now you must include the package responsible for formatting code in such a way. Add this line:

\usepackage{minted}

Defining the document

Once added, you must now define the section of your document, where text will be contained.
Simply add:

\begin{document}
\end{document}

So far your code should look like this:

\documentclass[a4paper]{article}

\usepackage{minted}

\begin{document}
\end{document}

Compiling your code at this stage won't generate a valid PDF, so we must fill out the document with something.

Adding a code snippet

As explained in the previous section, we used a \begin and \end statement to define the actual document. Within these encapsulating statements, you must now add:

\begin{minted}[frame=single,framesep=10pt]{cpp}
\end{minted}

All code written within these \begin and \end statements will be interpreted as C++ code. You can now start writing code snippets.

Final product

This is what your final result should look like:

\documentclass[a4paper]{article}

\usepackage{minted}

\begin{document}
\begin{minted}[frame=single,framesep=10pt]{cpp}

void exampleFunction();

\end{minted}
\end{document}

Now once you compile your LaTeX code, it will generate a PDF containing a code snippet with the code you've provided.

A preview of the expected result on Overleaf:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →