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

// Code...

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?


2 Answers 2


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:


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

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}]

Adding a label e.g., {lst:test} to the parameters of lstlisting works too if you call a script externally e.g., {test.py} as opposed to using a \begin{lstlisting} and \end{lstlisting} block as shown below:

\lstinputlisting[language=Python, caption=Example, label={lst:test}]{test.py}
  • 1
    Welcome, this was already covered in the accepted answer.
    – Troy
    Commented Mar 12, 2018 at 15:06
  • 3
    I think it is not very clear where there was the error. That's why I answered it :) Commented Mar 13, 2018 at 12:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .