# cross-referencing a listing item does not work

I want to cross-reference a listing item. I used the label in the \lstinputlisting, but the output shows ??. Here is the script:

\documentclass{article}
\usepackage{lipsum}
\usepackage{cleveref}
\usepackage{listings}
\usepackage{xcolor}

\begin{document}
\title{Test}
\maketitle

\section{Listing}
\lstset{language=Python}\label{ls:example}

\lstinputlisting[language=Python, label=my_listing_label, caption={caption.}]{/home/e/Documents/test_latex/test.py}

\section{Another Section}
We reference~\cref{my_listing_label}
\end{document}


Here is the test.py content:

if x==y:
print("hi")


Here is the output:

EDIT: Also, I need to add that I want the cross-referencing displayed as listing 1 not as section 1.

• Did you run it twice? – Sigur Mar 6 at 0:16
• @Sigur Yes I did. – seq Mar 6 at 0:20

# Load cleveref last

Loading cleveref last solves this issue.

# Some packages are best loaded after others

Not all packages play nice with one another. Some packages which are best included in the end (in the order I have found they need to be imported) include

\usepackage{hyperref}
\usepackage{cleveref} % After hyperref
\usepackage{caption}  % After cleveref.
\usepackage{geometry} % Last of all.


# A working example

\documentclass{article}
\usepackage{lipsum}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{cleveref} % <-- Now loaded last of all.

\begin{document}
\title{Test}
\maketitle

\section{Listing}
\lstset{language=Python}\label{ls:example}

\lstinputlisting[language=Python, label={my_listing_label}, caption={caption.}]{eg.py}

\section{Another Section}
We reference~\cref{my_listing_label}
\end{document}