[Tex/LaTex] Having trouble cross-referencing figures

cross-referencing

I'm having a bit of trouble trying to reference figures in my latex document. Here is my latex code:

\documentclass[12pt]{article}
\begin{document}

\begin{figure}
  Here is a figure
  \label{fig:test1}
  \caption{Here is a caption}
\end{figure}
Here is some text. See figure~\ref{fig:test1}.

\end{document}

I compile it twice with pdflatex test.tex but in the resulting pdf I get a blank space where there should be a number for the figure reference. For example, instead of "See figure 1." I get "See figure ."

How do I fix this problem?

Best Answer

You need to place your \label after \caption in order for the referencing to work:

\documentclass[12pt]{article}
\begin{document}

\begin{figure}
  Here is a figure
  \caption{Here is a caption}
  \label{fig:test1}
\end{figure}
Here is some text. See figure~\ref{fig:test1}.

\end{document}