Defining custom labels

I found a solution for the custom label what works with hyperref, been looking everywhere and I keep ending back to this page. (By google searching)

Solution by Ian (does not work with hyperref)

\makeatletter
\newcommand{\customlabel}[2]{%
\protected@write \@auxout {}{\string \newlabel {#1}{{#2}{}}}}
\makeatother

The reason it does not work with hyperref, is that the package change the \newlabel command so it has 6 parameters.

Modified version of Ian's answer, that works with hyperref package.

\makeatletter
\newcommand{\customlabel}[2]{%
   \protected@write \@auxout {}{\string \newlabel {#1}{{#2}{\thepage}{#2}{#1}{}} }%
   \hypertarget{#1}{#2}
}
\makeatother

However doing this means that the modified version requires hyperref package.

\hypertarget is added to make the links work when using \ref.


Do you really need to use \ref? You could just say \newcommand{\foobar}{22}, so that when you type \foobar you get 22. Of course this crude approach does not work if any references occur before the label is defined. To do it with \ref, try this.

\documentclass{minimal}
\makeatletter
\newcommand{\customlabel}[2]{%
\protected@write \@auxout {}{\string \newlabel {#1}{{#2}{}}}}
\makeatother
\begin{document}
Here is some text. \customlabel{foobar}{22}
Here is some more text \ref{foobar}.
\end{document} 

I guess the shortest solution is to use \def:

\documentclass[a4paper,oneside,11pt]{report}

\def \lfoo {22 }

\begin{document}
    In line \lfoo foo-bar. Furthermore, line \lfoo...
\end{document}

enter image description here