52

I'm using the following code to create a listing with sourcecode:

\begin{lstlisting}[caption={caption_text}\label{lst:a_label},language=Java] 
// Code...
\end{lstlisting}

Unfortunately, a \ref{lst:a_label} somewhere in my text does not return the correct number, or at least not the number I expected. The caption itself shows the correct number. How can I fix that?

89

I think the lstlisting environment prefers the label to be inserted as a normal parameter:

Adapt the following code to your needs and see if you obtain what you want:

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[caption={Some Java code},label={lst:label},language=Java]
// Code...
\end{lstlisting}
See code~\ref{lst:label}.
\end{document} 
1

The problem is that in the lstlisting declaration you should use label={example} instead of \label{example}.

\begin{lstlisting}[language={[Sharp]C}, caption={example is here}, label={example}]
  • 1
    Welcome, this was already covered in the accepted answer. – Troy Mar 12 '18 at 15:06
  • I think it is not very clear where there was the error. That's why I answered it :) – Joel Carneiro Mar 13 '18 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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