2

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: enter image description here

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
1

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.

For a bit more info see the answers to Which packages should be loaded after hyperref instead of before?.

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}

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.