5

I am using the cleveref and hyperref packages. This works well overall, but cross-references to lines in algorithms are incorrect.

I found some other related posts, this one and this one. However, solutions given there do not work for me.

Here is the MWE:

\documentclass[11pt]{report}

%% algorithms
\usepackage[chapter]{algorithm}
\usepackage{algpseudocode}

%% referencing
\usepackage{hyperref}
\usepackage{cleveref}


\begin{document}

\chapter{First chapter}

\begin{algorithm}[!htb]
    \caption{First algorithm}
    \begin{algorithmic}[1]
        \State A statement in 1st algorithm 
    \end{algorithmic}
\end{algorithm}


\chapter{Second chapter}
A reference to a line in \cref{alg:secondalg} \ : \cref{step:insecondalg}

\begin{algorithm}[!htb]
    \caption{Second algorithm} \label{alg:secondalg}
    \begin{algorithmic}[1]
        \State A statement in 2nd algorithm \label{step:insecondalg}
    \end{algorithmic}
\end{algorithm}

\end{document}

The \cref to the step in second chapter gives the right step number, but its link points to the algorithm in first chapter.

Please provide any solutions / workarounds that you may have.

1 Answer 1

6

You get a warning:

pdfTeX warning (ext4): destination with the same identifier (name{[email protected]})
has been already used, duplicate ignored

In this case hyperref doesn't create a suitable auxiliary counter for the anchors, but you can create it yourself: its name should be HALG@line and you want to link its representation to something unique, for instance the representation of the algorithm counter.

\documentclass[11pt]{report}

%% algorithms
\usepackage[chapter]{algorithm}
\usepackage{algpseudocode}

%% referencing
\usepackage{hyperref}
\usepackage{cleveref}

\makeatletter
\newcounter{HALG@line}
\renewcommand{\theHALG@line}{\thealgorithm.\arabic{ALG@line}}
\makeatother


\begin{document}

\chapter{First chapter}

\begin{algorithm}[!htb]
    \caption{First algorithm}
    \begin{algorithmic}[1]
        \State A statement in 1st algorithm 
    \end{algorithmic}
\end{algorithm}


\chapter{Second chapter}
A reference to a line in \cref{alg:secondalg} \ : \cref{step:insecondalg}

\begin{algorithm}[!htb]
    \caption{Second algorithm} \label{alg:secondalg}
    \begin{algorithmic}[1]
        \State A statement in 2nd algorithm \label{step:insecondalg}
    \end{algorithmic}
\end{algorithm}

\end{document}
1
  • Perfect, thank you
    – kksagar
    Commented Mar 3, 2022 at 8:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .