# hyperref to line number in listing imported from file

Can I refer to a line number from the imported file without escaping chars inside the file?

Say, I import my file like this

\lstinputlisting[language=c]{main.c}


and I want to \hyperref{} line 50 without modifying it or copying to my .tex file.

• Welcome to TeX.SX! I'm not sure that I understand. The whole point of using \ref{...} is to be able to dynamically refer to other parts of the document. From want you have said you simply want to refer to line 50 so why not write by line 50...? – Andrew Aug 15 '15 at 4:49
• @Andrew yeah, you are correct. What I actually want though is to hyperref this part of the document. Sorry for not asking this straight away. – orestisf Aug 15 '15 at 9:28

The following example sets a label for the listings by option label. The anchor name of the label is extracted and analyzed to get the internal listings number. In this case the unnumbered listings has anchor lstlisting.-1 with the number -1 for the listings. The anchor names for the line numbers follow the pattern lstnumber.<listings number>.<line number>. Macro \lstlinelink references the line, given the label for the listings and the line number. Two LaTeX runs are necessary because of the label.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[variablett]{lmodern}
\usepackage{listings}
\usepackage{refcount}[2006/02/20]

\makeatletter
\refused{#1}%
#2%
\else
#2%
}%
\fi
}
\makeatother

\begin{document}
\noindent