Lstlistings reference to line number

How can I place a 'label' marker inside a lstlisting environment (external file imported and formatted via the listinputlisting command) so that I can cross-reference a particular line number?

In other words, I would like to be able to use the following sort of text content in my document.

"By referring to line LINE_NUMBER, in listing ABC, the use of DEF object has resulted in GHI objectives being met" etc...

Where the LINE_NUMBER would be marked in the file to the effect of \label{line:marker} and then used in the document with \ref{line:marker}.

It may require the use of an encapsulating flag/s, such as <\label{line:marker}> to differentiate from surrounding actual code, which is fine with me.

Cheers.

• – Werner Nov 10 '13 at 2:26

You can use escapechar=<char> to use commands.

\documentclass{scrartcl}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[
language=Java,escapechar=|] %language and your escape char
public class Main {
public static void main(String [] args) {
System.out.println("Hello world !");|\label{line:sp}|   %% <--- label here
}
}
\end{lstlisting}

By referring to line~\ref{line:sp}, in listing ABC, the use of DEF object has resulted in GHI objectives being met" etc...
\end{document}


• Note that the escape char \$ does not work if this is for labels. – Mikaël Mayer Aug 2 '16 at 9:45