# Reference lstlisting code by caption/title instead of number

In my LaTeX document I use \ref{code.java} to reference a code as shown in the image below and it shows the section/chapter number. Why it shows "1" instead of code.java? Is it possible to make the code name appear instead of the number of section/chapter?

This is my LaTeX code using lstlisting and setting a label name:

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{xcolor}

\definecolor{verde}{rgb}{0.25,0.5,0.35}
\definecolor{jpurple}{rgb}{0.5,0,0.35}
\usepackage{listings}
\lstset{
language=Java,
basicstyle=\ttfamily\small,
keywordstyle=\color{jpurple}\bfseries,
stringstyle=\color{red},
morecomment=[s][\color{blue}]{/**}{*/},
extendedchars=true,
showspaces=false,
showstringspaces=false,
numbers=left,
numberstyle=\tiny,
breaklines=true,
backgroundcolor=\color{cyan!10},
breakautoindent=true,
captionpos=b,
xleftmargin=0pt,
tabsize=4
}

\title{example}
\author{marcellocamara}
\date{March 2019}

\begin{document}

\maketitle

\section{Introduction}

Let's cite the code \ref{code.java} as example.

\begin{lstlisting}[title = {code.java}, label={code.java}]
public class MyClassName {

Some java code.

}
\end{lstlisting}

\end{document}

• please share the complete code starting with \documentclass to \end{document}. – subham soni Mar 27 '19 at 3:59
• It's more than 3500 lines... I can edit and post an example with that I want. It will help ? the problem is already writed. I just need to change the reference to lib lstlisting – cellocamara Mar 27 '19 at 4:28
• Yes a minimal working example is required. – subham soni Mar 27 '19 at 4:29
• I shared the simple example. – cellocamara Mar 27 '19 at 4:42

\ref references listings by its automatically assigned number. Usually a caption is assigned to listings with the caption={My caption} option which makes the caption look like

Listing 1: My caption

As you are using the title option, the numbering is suppressed from being output and instead the literal title is shown.

One option to reference the caption is to use the \nameref command from the nameref package:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{nameref}

\definecolor{verde}{rgb}{0.25,0.5,0.35}
\definecolor{jpurple}{rgb}{0.5,0,0.35}
\usepackage{listings}
\lstset{ ... }

\begin{document}
\section{Introduction}

Let's cite the code \nameref{code.java} as example.

\begin{lstlisting}[caption={code.java (caption)}, title={code.java (title)}, label={code.java}]
public class MyClassName {

Some java code.

}
\end{lstlisting}
\end{document}


As you can see, \nameref uses the provided caption for the reference, not the title. So if you want both to be the same, you have to duplicate the text for caption and title.

• That's worked perfectly. – cellocamara Mar 27 '19 at 14:38