# Reference to longtable wrong if \numberwithin{table}{section} is activated

I've encountered something weird while using the longtable package together with \numberwithin{table}{section} or \counterwithin{table}{section}: if a longtable is the first table in a section, it will not be referenced correctly (with \ref{}); instead the reference will point to the last first-in-a-section longtable in the document. Note that the error is carried forward to other packages which rely on longtable such as tabu (longtabu).

While searching for a solution, I found duplicate entries for the first-in-a-section longtables in the aux-file, which is why I am suspecting this to be a bug. However, my LaTeX knowledge is limited and I am happy to be proven wrong.

Here's my MWE:

\documentclass{article}
\usepackage{amsmath}
\numberwithin{table}{section}
\usepackage{booktabs}
\usepackage{longtable}

\begin{document}
Reference to Table \ref{tab:Label1}\\
Reference to Table \ref{tab:Label2}\\

\clearpage
\section{}

\begin{longtable}{ll}
\caption{Caption.}
\label{tab:Label1}\\
\toprule
\midrule
\multicolumn{2}{c}{\begin{footnotesize}\tablename\ \thetable\ -- \textit{Continued from previous page}\end{footnotesize}} \\
\toprule
\midrule
\bottomrule
\multicolumn{2}{r}{\begin{footnotesize}\textit{Continued on next page}\end{footnotesize}} \\
\endfoot
\bottomrule
\endlastfoot
some variable & some explaination\\
\midrule
some variable & some explaination \\
\end{longtable}

\clearpage
\section{}

\begin{longtable}{ll}
\caption{Caption.}
\label{tab:Label2}\\
\toprule
\midrule
\multicolumn{2}{c}{\begin{footnotesize}\tablename\ \thetable\ -- \textit{Continued from previous page}\end{footnotesize}} \\
\toprule
\midrule
\bottomrule
\multicolumn{2}{r}{\begin{footnotesize}\textit{Continued on next page}\end{footnotesize}} \\
\endfoot
\bottomrule
\endlastfoot
some variable & some explanation\\
\midrule
some variable & some explanation \\
\end{longtable}

\end{document}


On my computer, both references point to the latter table.

• Do your computers replicate the error?
• Does anybody have an idea what could cause this error?
• Would anybody know a workaround?
• Welcome to TeX.SX! Usually, we don't put a greeting or a “thank you” in our posts. While this might seem strange at first, it is not a sign of lack of politeness, but rather part of our trying to keep everything very concise. Accepting and upvoting answers is the preferred way here to say “thank you” to users who helped you. – Martin Schröder Dec 3 '15 at 21:49
• Put the \numberwithin command after loading hyperref. – egreg Dec 3 '15 at 21:55

As a general rule, settings should be made after loading packages (there are some exceptions); this is a case: since hyperref modifies the macros that manage counters, your \numberwithin given before the package is loaded leads to the issue.
\documentclass{article}