Why does \pageref{LastPage} give me “??” rather than page number of the last page?

I am trying to use the lastpage package in order to have footers with the page number given in the form "Page x of y", where y is the page number of the last page.

This should be straightforward, but I'm getting instead: "Page x of ??"; i.e., I'm getting a pair of question marks rather than a page number.

I've distilled the problem down in order to minimize dependencies, etc. to:

\documentclass{article}
\usepackage{lastpage}
\usepackage{fancyhdr}
\pagestyle{fancy}
\cfoot{\thepage\ of \pageref{LastPage}}
\begin{document}
text
\newpage
text
\newpage
text
\end{document}


Does anyone have any idea about what I could be missing to cause \pageref{LastPage} to give me "??"?

-
Did you run it twice? – Peter Grill Sep 16 '11 at 22:14
Your code compiles OK in my system. Have you compiled it twice? – Gonzalo Medina Sep 16 '11 at 22:14

In order for TeX to know what the last page is, the document must be completed. So you need to run LaTeX twice. The first time it will write out an temporary .aux file and on the second run it will read it in and fill in the ??. When I run your document the second time it correctly displays Page 1 of 3.

Running it twice should suffice for most applications, but sometimes additional runs are required so keep that in mind in case this comes up again.

The same applies to other references such as equation numbers, section numbers, etc...

Here is a good question that explains a bit about some of these temporary files that get generated.

-
Thanks! This did the trick.(I had reinstalled my LaTeX editor, Latexian, from scratch and neglected to reset the preference where the LaTeX would be compiled twice by default.) – Jim Ratliff Sep 16 '11 at 22:21
@Jum Ratliff: When encountering this issue after two compiler runs (some files need three or even four compiler runs!), please look at the end of the .log file for warnings of package rerunfilecheck and for LaTeX Warning: There were undefined references. LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right. – Stephen Sep 17 '11 at 11:26