# How to avoid interference between amsmath/fleqn and refstepcounter/label?

When I pdflatex the following twice:

\documentclass[fleqn]{article}

\usepackage{amsmath}

\begin{document}

\newcounter{mycounter}

\refstepcounter{mycounter}\label{foo}\ref{foo}

\refstepcounter{mycounter}\label{bar}\ref{bar}

$$x\refstepcounter{mycounter}\label{baz}\ref{baz}$$

\ref{baz}

\refstepcounter{mycounter}\label{qux}\ref{qux}

\end{document}


then I get the following output:

1
2
x1
1
4


If I remove \usepackage{amsmath} or [fleqn] or both then I get

1
2
x3
3
4


The latter is what I want.

Can anyone tell me how to get the latter when using amsmath/fleqn ?

• Welcome to TeX.SE! Oct 26, 2021 at 17:37

amsmath allows the end user to insert their own tags for numbered equations and therefore collects the body of math environments before processing them. This allows for proper parsing of the content, possibly delaying the execution of \label only after the equation counter has been stepped. It does, however, retain access to the original LaTeX \label via \ltx@label, which is appropriate for your use:

\documentclass[fleqn]{article}

\usepackage{amsmath}

\makeatletter
\makeatother

\begin{document}

\newcounter{mycounter}

\refstepcounter{mycounter}\label{foo}\ref{foo}% 1

\refstepcounter{mycounter}\label{bar}\ref{bar}% 2

$$x\refstepcounter{mycounter}\ltxlabel{baz}\ref{baz}$$

\ref{baz}% 3

\refstepcounter{mycounter}\label{qux}\ref{qux}% 4

\end{document}


\ltxlabel (or \ltx@label) will be executed immediately, using whatever counter was previously stepped (via \refstepcounter) as a label reference. In contrast, \label will only be used to reference the equation counter under amsmath.