[Tex/LaTex] cleveref fails to reference algorithms

algorithmicxalgorithmscleverefcross-referencinghyperref

In the following example document, both \autoref and plain ref will correctly link and number an algorithm reference, but cleveref fails that task. It will just insert question marks instead. In another, far more complex document I have, it does insert correct numbers but links them all to page 1. Since the documentation of cleveref sounds like it should support everything other referencing packages support and more, I'd have hoped this was supported, too.

\documentclass{article}
\usepackage[nameinlink,noabbrev]{cleveref}
\usepackage{hyperref}
\usepackage{algorithm}
\usepackage{algpseudocode}
\providecommand\algorithmname{algorithm}
\begin{document}
We want the real content on page two to better detect errors.
\newpage

\begin{algorithm}
  \caption{Incrementation step}\label{alg:inc}
  \begin{algorithmic}
    \State $x\gets x+1$
  \end{algorithmic}
\end{algorithm}
Comparing auto like \autoref{alg:inc},
clever like \cref{alg:inc} % this gives the error message
and manual like algorithm~\ref{alg:inc}.
\end{document}

Compiling the above I get

LaTeX Warning: Reference `alg:inc' on page 1 undefined on input line 18.

If I move the algorithm package before cleveref, I get an error instead of that warning:

(/usr/share/texmf-dist/tex/latex/cleveref/cleveref.sty
! Undefined control sequence.
<argument> \ALG@beginalgorithmic 

l.2843   }{}
            %  end of \@ifpackageloaded{algorithm}

But if I move the algpseudocode before cleveref, I'm back to the beginning.

This is a Gentoo texlive 2012 installation, with the following packages involved:

  • cleveref 2012/03/07 v0.18.5
  • hyperref 2012/05/13 v6.82q
  • algorithm 2009/08/24 v0.1
  • algorithmicx 2005/04/27 v1.2

Best Answer

You have to use the correct loading order; check also Which packages should be loaded after hyperref instead of before?

\documentclass{article}

\usepackage{algorithm}
\usepackage{algpseudocode}

% hyperref must go last
\usepackage{hyperref}

% but cleveref goes "laster" than hyperref
\usepackage[nameinlink,noabbrev]{cleveref}

\providecommand\algorithmname{algorithm}

\begin{document}
We want the real content on page two to better detect errors.
\newpage

\begin{algorithm}
  \caption{Incrementation step}\label{alg:inc}
  \begin{algorithmic}
    \State $x\gets x+1$
  \end{algorithmic}
\end{algorithm}
Comparing auto like \autoref{alg:inc},
clever like \cref{alg:inc}
and manual like algorithm~\ref{alg:inc}.
\end{document}

enter image description here