You can include more or less any LaTeX macro you want inside your listing by defining a way to escape from verbatim code formatting to usual LaTeX processing. Here is an example using escapeinside
to define two sequences of chars that start (/*!
) and end (!*/
) the escape area. I usually use the usual comment delimiters of the respective language plus some characters I usually don't use in comments, such that the code still looks good in editors without LaTeX parsing (but you can really use any delimiters you like).
Update: You can also use the options escapebegin
and escapeend
to add some LaTeX macros around the escaped sequence. Suppose you always use the escape in comments and have comments printed in gray, you can pass the escapebegin=\color{gray}
option to have the escaped text printed in the same color.
Minimal example:
\documentclass{article}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
language=C++,
commentstyle=\color{gray},
escapeinside={/*!}{!*/},
escapebegin=\color{gray},
}
\begin{document}
\begin{figure}[h]
\centering
\includegraphics[width=0.3\textwidth]{example-image-a}
\caption{My figure}
\label{figx}
\end{figure}
\begin{lstlisting}
void test() {
figure->display(); // Output: /*!\ref{figx}!*/
}
\end{lstlisting}
\end{document}
