4

Is there any way to use a macro within a \label tag?

\edef\num{1}
\label{test\num}
\ref{test1}
  • 1
    Yes there is. The argument of the \label is written to the .aux file and expanded during that. You example should work. Maybe you use some packages which change \label? If it doesn't work for you, add a minimal example of your code. – Martin Scharrer Apr 13 '11 at 9:08
4

The following works as expected:

\documentclass[a4paper]{article}

\begin{document}
\def\NUM{1}
\section{X}\label{sec:\NUM}

This is section~\ref{sec:\NUM} or is it section~\ref{sec:1}?
\end{document}

If I load hyperref it works the same. Notice that defining \NUM with \edef or \def is exactly the same.

|improve this answer|||||
2

In case there is some problem scheduling expansion, you can use \expandafter to expand macros before passing them to a \label:

\def\num{1}
\def\labeltext{{test\num}}
\expandafter\label\labeltext
\ref{test1}
|improve this answer|||||
  • You're missing the braces: it should be \expandafter\label\expandafter{\labeltext} – egreg Aug 31 '11 at 20:49
  • @egreg: Right. It's cleaner, I think, to change the def of '\labeltext'. – Charles Stewart Sep 1 '11 at 5:41
  • Well, not in that way! :) – egreg Sep 1 '11 at 6:09
  • I've taken the liberty to edit your code. – egreg Sep 1 '11 at 6:37
  • @egreg: Ouch, right again. I've been writing code to unescape HTML: it mangles the thought processes. – Charles Stewart Sep 1 '11 at 20:18

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.