Indeed, you need to pass the expansion of \theexercise
, because hyperref
doesn't do it to the title.
\documentclass{article}
\usepackage{hyperref}
\newcounter{exercise}
\newcommand\exercise{%
\par % just in case
\refstepcounter{exercise}%
\begingroup\edef\x{\endgroup
\noexpand\section*{\unexpanded{Exercise} \theexercise}%
}\x
}
\begin{document}
\exercise\label{ex:first}
foo
\exercise\label{ex:second}
see \nameref{ex:first}
\exercise\label{ex:third}
bar
\end{document}
This is the (abridged) contents of the .aux
file:
\newlabel{ex:first}{{1}{1}{Exercise 1}{section*.1}{}}
\newlabel{ex:second}{{2}{1}{Exercise 2}{section*.2}{}}
\newlabel{ex:third}{{3}{1}{Exercise 3}{section*.3}{}}
It was
\newlabel{ex:first}{{1}{1}{Exercise \theexercise }{section*.1}{}}
\newlabel{ex:second}{{2}{1}{Exercise \theexercise }{section*.2}{}}
\newlabel{ex:third}{{3}{1}{Exercise \theexercise }{section*.3}{}}
with your code.
Note. Why \unexpanded{Exercise}
? In the particular case it is obviously unnecessary, but it would be for the German “Übung”.
You might use cleveref
instead.
\documentclass{article}
\usepackage{hyperref}
\usepackage[nameinlink]{cleveref}
\newcounter{exercise}
\newcommand\exercise{%
\par % just in case
\refstepcounter{exercise}%
\section*{Exercise \theexercise}
}
\crefname{exercise}{Exercise}{Exercises}
\begin{document}
\exercise\label{ex:first}
foo
\exercise\label{ex:second}
see \cref{ex:first}
\exercise\label{ex:third}
bar
\end{document}
The output is the same in both cases.

Can we avoid the \edef\x{\endgroup
trick? Yes, of course.
\documentclass{article}
%\usepackage{xparse} % not needed for LaTeX 2020-10-01 or later
\usepackage{hyperref}
\usepackage[nameinlink]{cleveref}
\ExplSyntaxOn
\NewDocumentCommand{\exercise}{}
{
\gooz_exercise:ne { \exercisename } { \theexercise }
}
\cs_new_protected:Nn \gooz_exercise:nn
{
\par % just in case
\refstepcounter{exercise}
\section*{#1~#2}
}
\cs_generate_variant:Nn \gooz_exercise:nn { ne }
\ExplSyntaxOff
\newcommand{\exercisename}{Exercise}
\newcounter{exercise}
\crefname{exercise}{\exercisename}{\exercisename s}
\begin{document}
\exercise\label{ex:first}
foo
\exercise\label{ex:second}
see \cref{ex:first} or \nameref{ex:first}
\exercise\label{ex:third}
bar
\end{document}
Note that cleveref
is not necessary, just remove the relevant calls if you prefer \nameref
.