How to make label numbers consistent in lstlisting?

I have defined two languages using \lstdefinelanguag and then setting them using \lstset. The point is that later when I write some listing and label them such as.

\begin{lstlisting}[language=JavaScript,label={lst:animate}]
\\just some function
\end{lstlisting}


The label numbers are not consistent when I reference them with \ref. Both the first and the second listing in my document get value 1. I assume because they are different languages. But then, I have 3 listings from the same language, and again they all have listing value. Any idea how to make listing values increase consistently?

• @clemens It's kind of too long to provide a MWE, but yes, they do coincide. They are in the same section. I though listings work more or less like figures and don't depend on the section. Any idea how to work around this? – typos May 30 '17 at 15:41
• It's never too long for a MWE, look at the example in my answer… – clemens May 30 '17 at 15:46

Just a wild guess since you didn't provide a MWE but do the referenced numbers coincide with the section number the listing is in? In order to be able to referende a listing it needs to have a caption! The one in your question doesn't have one so the label references whatever counter has been refstepped last.

\documentclass{article}
\usepackage{listings}

\begin{document}

\section{bla}
\section{bla}

\begin{lstlisting}[label=lst:foo]
foo
\end{lstlisting}

First listing without caption: \ref{lst:foo} -- ups! Section number!

Second listing with caption: \ref{lst:bar} -- this looks right!

\begin{lstlisting}[label=lst:bar,caption=bar]
bar
\end{lstlisting}

\end{document}


A caption and several other numbered document elements do \refstepcounter{...} with the corresponding counter and a label always refers to the counter for which this has been done the last time before \label is used. If the listing has no caption then this can be a \section like in my example or something else depending on your actual document. It makes sense: if you refer to listing 1 then there should be a listing 1 marked as such with a caption. Otherwise you will only confuse your readers.