4

My question is a follow-up to this question.

I want to write variables to aux file and also declare them there because the number of variables varies and their csnames are defined in the document body automatically during build process. I have a control sequence that iterates through generated variables and writes declare and store commands (using c-type argument instead of N) to aux file. Everything works well except that I get errors similar to this:

Control sequence \g_test_int already defined.

The aux file itself looks correct (this is from MWE):

\relax

\ExplSyntaxOn

\int_new:N \g_test_int

\ExplSyntaxOff

MWE:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\AtEndDocument{
    \iow_now:cx{@auxout}{
        \token_to_str:N \ExplSyntaxOn
        ^^J
        \int_new:N\g_test_int
        ^^J
        \token_to_str:N \ExplSyntaxOff
    }
}
\ExplSyntaxOff


\begin{document}
Hello
\end{document}
2
  • 1
    the aux file is read twice, once at the start and once at the end, so how to avoid the error depends a bit on what you want to happen in each case. Jul 6, 2018 at 11:01
  • I want the variables declared and defined only between preamble and document body (at \begin{document} -phase). Isn't that the first time aux file is read? Jul 6, 2018 at 11:09

1 Answer 1

3

There are two problems with your code:

  1. TeX tries to interpret \g_test_int, because you're doing \iow_now:cx

  2. When TeX rereads the .aux file, \int_new:N will raise an error.

Solution:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\AtEndDocument{
    \iow_now:cn{@auxout}{
        \ExplSyntaxOn
        ^^J
        \int_zero_new:N \g_test_int
        ^^J
        \ExplSyntaxOff
    }
}
\ExplSyntaxOff


\begin{document}
Hello
\end{document}

At rereading, \g_test_int will be zeroed, but it's unimportant as all typesetting has already been done.

On the other hand, it's unclear why you would declare a variable in the .aux file: if this file does not yet exist, no macro in the document body can use the variable.

3
  • I have macro that first checks if variable exists and if it doesn't then it uses 0 instead. Jul 6, 2018 at 11:25
  • @Jarno_C-137 Still I don't understand why not directly doing \int_new:N \g_test_int in the preamble.
    – egreg
    Jul 6, 2018 at 12:33
  • In my actual documents names and amount of the variables is not known beforehand. These change between documents and I'm building a package that manages all of them. This was just very minimal example that reproduced the problem. Jul 6, 2018 at 13:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .