[Tex/LaTex] label within lstlisting prefix gives strange output on \ref


I have all kinds of labeltypes for my own convenience defined like "sec:", "cha:", "fig:", "lst:" and so on.

Now I wanted to point to a certain line of code within one of my listings. There is no need have a label for that listing, but on some other page I want to put "(see on page X)" especially because of the listing might be split by a natural pagebreak.

At the end of the line of code I wrote $\label{lbl:mySpecialLineOfCode}$. At the location where I want to put the page number by \pageref{lbl:mySpecialLineOfCode} and it outputs the correct page number.

For experimental reasons I put \ref{lbl:mySpecialLineOfCode} and it printed 14. I don't understand how Latex determines this number. The label is placed neither in chapter in 14, nor in section X.14, nor is it the 14th label or the 14th listing (I have a larger number of both before that position).

My only fear is, that it occupies a "place"/"number" and the listofwhatever at the beginning in the document will go from 13 to 15 in the next line. That would be too bad. Better I know beforehand that something like this can happen (I cannot say it happens – in my case though).

Anybody can give me a hint?

Best Answer

LaTeX's \label-\ref system by default works along the following lines:

  • With the issue of \label{<lab>}, LaTeX stores the last updated counter that used \refstepcounter and the associated page number in the .aux file. \label actually uses \@currentlabel, which is set by \refstepcounter. This step only occurs at page shipout to ensure that the correct page number is associated with the label;
  • An issue of \ref retrieves the counter written during \label (\@currentlabel) while \pageref retrieves the accompanying page number.

listings has a counter for each lstlisting (the counter lstlisting), but also a counter for each line of a specific listing (the counter lst@lineno).

If you wish to reference the counter for the listing, place your \label immediately after the listing \caption. If you wish to reference the counter for a line within the listing, place your \label on the appropriate line.