# Using \newcommand with \write\@auxout inside

I have read some related posts but still cannot resolve the problem with

\newcommand{\myLabel}[2]{\makeatletter\write\@auxout{\string\newlabel{#1}{{#2}{\thepage}}}\makeatother}

I would like to write a line to .aux that will be later read as a label. When executed on page 11 in subsection 3.1,

\myLabel{Rings}{\thesubsection.2}

would write the line

\newlabel{Rings}{{3.1.2}{11}}

I am unable to make this work. Could you kindly explain what I do wrong and perhaps correct the problem?

It's actually easier (and better) to just use the \label-\ref system. It's easier because you don't have to worry about how to write out to the .aux, and it's better because it writes out to the .aux at the right time so the page references are correct. Here's how to do it:

\documentclass{article}

\makeatletter
\newcommand{\myLabel}[2]{%
\def\@currentlabel{#2}% Update label
\label{#1}}% Mark label
\makeatother

\begin{document}

\myLabel{abc}{def}\ref{abc} \par

\section{Lord}
\subsection{of the}
\subsubsection{Rings}
\myLabel{Rings}{\thesubsubsection.2}\ref{Rings}

\end{document}

Note that the \makeatletter...\makeatother pair has to be outside the macro definition. And updating \@currentlabel is the only thing needed to correctly establish the reference. The .aux file for the above MWE contains:

\relax
\newlabel{abc}{{def}{1}}
\@writefile{toc}{\contentsline {section}{\numberline {1}Lord}{1}}
\@writefile{toc}{\contentsline {subsection}{\numberline {1.1}of the}{1}}
\@writefile{toc}{\contentsline {subsubsection}{\numberline {1.1.1}Rings}{1}}
\newlabel{Rings}{{1.1.1.2}{1}}
• Beautiful! Thank you so very much for your answer --- and so quick at that. I just tried you solution, and it solved the problem perfectly. I have also learned something new about the \label command and cannot thank you enough for all the above. – Peter Jun 25 '14 at 2:47