[Tex/LaTex] Reference to a listing returns wrong number

cross-referencinglistings

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

\begin{lstlisting} 
// 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?

Best Answer

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} 
Related Question