# Cross referencing in numbered environment

I picked up a template to write exams a while ago only. Each problem is written between \begin{problem} and \end{problem}. In the preamble I have

\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{marvosym}
\usepackage{enumerate}
\usepackage{subfigure}
\usepackage{placeins}
%\pagestyle{empty} %<== DELETE IF YOUR TEST HAS MORE THAN ONE PAGE

%puts in a horizontal  rule the width of the text with space
%before and after.
\newcommand{\sep}{\ifhmode\par\fi\vskip6pt\hrule\vskip6pt}

%A new environment for a test problem.
\newcounter{problem}
\newenvironment{problem}
{
%\stepcounter{problem}%
\refstepcounter{problem}
\filbreak%
\sep
\noindent\arabic{problem}.
}
{
\filbreak
}

\begin{document}


I replaced \stepcounter{problem} with \refstepcounter{problem}. I do the following when I try to cross-reference:

\begin{document}
\begin{problem}
\label{labelname}
\end{problem}
\begin{problem}
Refer to problem~\ref{labelname}. Now answer this question.
\end{problem}
\end{document}


However, when I compile the .tex file, the PDF file shows "Refer to problem ??. Now answer this question."

How could I fix this? I appreciate the help.

-

But when run again (without deleting the .aux files that are produced in the first run), you obtain the desired results:
Since it is possible to reference a figure before it is placed, two runs are required. The first determines the figure numbers placing a temporary ?? as a placeholder for the reference, and the second resolves the references.