I am running into a rather weird error that apparently originates from the combination of \include
, \let\clearpage\relax
and a referenced label after a page break.
In this particular example, the label mylabel
defined in the listing cannot be referenced anymore when the reference and the label are close enough to a page break.
The MWE consists of two files, the main-file and an included file.
I am using the \let\clearpage\relax
command to avoid page breaks after every \include
.
The error does not occur if the file is \input
instead of \include
d.
\documentclass[11pt,twoside]{book} %
\usepackage[utf8]{inputenc} % Enoding
\usepackage[english]{babel} % Language
\usepackage{listings}
\usepackage{forloop}
\begin{document}
\begingroup
\let\clearpage\relax
\include{includedfile} % changing include for input would work
\endgroup
\end{document}
Included file:
\newcounter{ct}
\forloop{ct}{1}{\value{ct} < 40}%
{%
.\\
}
Listing \ref{mylabel}.
\begin{lstlisting}
some code;
\end{lstlisting}
Running this example will have an output where the label cannot be referenced (even after multiple runs):
Now, one solution is to use \input
as mentioned earlier but I am rather interested in why this happens.
Does the \clearpage
command fulfil an important function for references to work?
And can the error be avoided without removing \let\clearpage\relax
while using \include
?
EDIT: I just found this question with the same issue (though it does not have a definite answer).
Best Answer
\include
uses a separate.aux
file. If the file is not included, the.aux
file is still read and the references of the.aux
file are available.Entries into the
.aux
file can be written\immediate
or at the time, when the page is shipped out. Therefore\include
starts a new page. Thus the labels of the previous page goes into the previous.aux
file. Then the.aux
files are switched immediately (\immediate\openout
). The labels go into the.aux
file of the included file. After the included file is processed,\include
calls\clearpage
to output any stuff of the included file including labels, which goes into the.aux
file of\include
. Then again the.aux
files are switched, the include.aux
file is immediately closed and the next writes to an.aux
file is going to the main.aux
file.With
\let\clearpage\relax
you destroy the capabilities of\include
. In the case of the question, the last page of the included file contains the label. The shipped out page contains the command to write the label to fileincludedfile.aux
. But the page is not yet shipped out before the end of\include
and the file handle forincludedfile.aux
is closed. TeX then redirects the write request to a closed file handle at the next page shipout to the.log
file, where you will find:Also the entry into the list of listings will be missing.
Summary:
As addendum the code for the "flashy thing" as requested by kan:
Then