[Tex/LaTex] 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:

\cfoot{\thepage\ of \pageref{LastPage}}

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

Best Answer

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.