Define global commands in aux file

I'd use a different strategy: use a wrapper command, rather than directly defining macros.

\documentclass{article}

\makeatletter
\newcommand{\usevalue}[1]{%
  \ifcsname [email protected]#1\endcsname
    \csname [email protected]#1\endcsname
  \else
    ??%
  \fi
}
\newcommand{\definevalue}[2]{%
  \write\@auxout{%
    \unexpanded{\global\@namedef{[email protected]#1}{#2}}%
  }
}
\makeatother

\begin{document}

Something with \usevalue{tester}.

Something else.

Now we can define \texttt{tester} and use again it: \usevalue{tester}.

\definevalue{tester}{42}

\end{document}

Output of first run

enter image description here

Output of second run

enter image description here


You could write

\makeatletter
\newcommand{\doccommand}[2]{%
  \immediate\write\@auxout{\gdef\noexpand#1{\unexpanded{#2}}}%
  \gdef#1{#2}%
}
\makeatother

This will do a global define without expanding the replacement text. I added an additional direct \gdef so that the command can be used without rerunning TeX.

But this is not a good idea: If you never use the command before the point where it is defined, defining it in the aux-file is useless. If you use the command before defining it, LaTeX never reaches the point where you write the aux-file entry.

So you can only use the command after running TeX once with the command defined but not used. If you ever delete the aux-file, your document is broken. If you ever only include a different chapter, the aux-file entry will not be written, so your document is broken.

Instead you could create a separate file with the definitions which you include in the preample. It's more work, but it results in a much more stable document.