\newcounter{chrefcnt}
\newcommand{\chref}[1]{%
\ifcsname chref@#1\endcsname
% do nothing, the command is already defined
\else
\stepcounter{chrefcnt}%
\expandafter\xdef\csname chref@#1\endcsname{\thechrefcnt}%
\fi
% now print the number
\csname chref@#1\endcsname}
With \chref{one} \chref{two} \chref{one}
you would get the output 1 2 1.
It's better to use prefixes, so as not to conflict with existing macros, I've used chref@
. Some more checks might be needed. There's no need to use the \label
-\ref
system, in this case. We simply define the command corresponding to the label to expand to the assigned number.
(Thanks to lockstep for having pointed out a name conflict.)
New implementation
Following the suggestion by Richard, here is a new implementation with an optional argument for "subcoumpounds"
\documentclass{article}
\makeatletter
\newcounter{chref@cnt}
\def\chrefstyle{\textbf}
\newcommand{\chref}[2][]{%
\ifcsname chref@#2\endcsname
% do nothing, the compound is already defined
\else
\stepcounter{chref@cnt}%
\expandafter\xdef\csname chref@#2\endcsname{\arabic{chref@cnt}}%
\expandafter\gdef\csname chrefsub@#2\endcsname{0}%
\fi
% now print the number
\chrefstyle{\csname chref@#2\endcsname}%
\if\relax\detokenize{#1}\relax
% do nothing, there's no optional argument
\else
\ifcsname chref@#2@#1\endcsname
% do nothing, the subcompound is already defined
\else
\@tempcnta=\csname chrefsub@#2\endcsname
\advance\@tempcnta\@ne
\expandafter\xdef\csname chref@#2@#1\endcsname{\@alph\@tempcnta}%
\expandafter\xdef\csname chrefsub@#2\endcsname{\number\@tempcnta}%
\fi
% now print the letter
\chrefstyle{\csname chref@#2@#1\endcsname}
\fi}
\makeatother
\begin{document}
\chref[X]{one} $\to$ 1a
\chref[Y]{one} $\to$ 1b
\chref{two} $\to$ 2
\chref[Z]{one} $\to$ 1c
\chref{one} $\to$ 1
\chref[A]{two} $\to$ 2a
\end{document}
For each main compound we remember the number of subcompounds already defined, initializing it to 0; for \chref{one}
we define \chrefsub@one
to be 0
. If a subcompound is requested and not yet defined, we set to the remembered number so far of subcompounds the temporary count register \@tempcnta
and advance it by one. We define the corresponding control sequence (for \chref[X]{one}
it would be \chref@one@X
) to expand to the alphabetic representation of the value of \@tempcnta
and remember the value of the "subcompounds-so-far".