[Tex/LaTex] How to use underscore in listings package properly

listingsunderscore

I understand that underscore is a special character in LaTeX, but how can I input underscores within lstlisting blocks without changing the code block itself?

Here is a short example:

Settings:

\lstset{
    frame=l,
    language=C++,
    basicstyle=\fontsize{11}{11}\selectfont\ttfamily,
    aboveskip=3mm,
    belowskip=3mm,
    showstringspaces=false,
    columns=fixed,
    numbers=left,
    numberstyle=\tiny\color{gray},
    keywordstyle=\color{blue},
    commentstyle=\color{dkgreen},
    stringstyle=\color{mauve},
    breaklines=true,
    breakatwhitespace=true,
    tabsize=4,
    texcl=true 
}

Code snippet:

\begin{lstlisting}
shared_ptr<vector> p; // this is a shared_ptr
\end{lstlisting}

If you could provide an answer works for both lstlisting and lstinline could be the best.

Best Answer

Your problem stems from the fact that you have

texcl=true

as part of your listings settings. Let's see what the listings documentation mentions about texcl:

texcl=<true>|<false> or texcl (default is false)
activates or deactivates LaTeX comment lines. If activated, comment line delimiters are printed as usual, but the comment line text (up to the end of line) is read as LaTeX code and typeset in comment style.

Of course, if you have texcl set and _ in your comments, then you'll be forced to adhere to LaTeX's rules for underscores in text. My suggestion would be to remove the texcl option:

enter image description here

\documentclass{article}
\usepackage{listings,xcolor}
\lstset{
  frame=l,
  language=C++,
  basicstyle=\ttfamily,
  numbers=left,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{green}\ttfamily,
  stringstyle=\color{mauve},
  %texcl=true 
}
\begin{document}
\begin{lstlisting}
shared_ptr<vector> p; // this is a shared_ptr
\end{lstlisting}
\end{document}

Alternatively, you can use texcl but should be aware of special processing of LaTeX-related uses in the comments:

enter image description here

\documentclass{article}
\usepackage{listings,xcolor}
\lstset{
  frame=l,
  language=C++,
  basicstyle=\ttfamily,
  numbers=left,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{green},
  stringstyle=\color{mauve},
  texcl=true 
}
\begin{document}
\begin{lstlisting}
shared_ptr<vector> p; // this is a \verb|shared_ptr|
\end{lstlisting}
\end{document}