[Tex/LaTex] Reference (\ref) doesn’t appear

cross-referencing

I have this very basic document:

\documentclass[12pt]{article}
\begin{document}
\label{a}
Reference \ref{a}
\end{document}

However after compiling it several times, the document I obtain only has "Reference" and not "Reference 1". What am I missing?

Best Answer

You are referencing nothing, since there is no counter increased with \refstepcounter for that small document. \label needs \refstepcounter, since that macro defines \@currentlabel, which holds the counter value (or better: reference format) (Of course, \@currentlabel can be defined beforehand in order to create 'fake' labels)

Now, latex.ltx defines an empty \@currentlabel before \begin{document} and that information is used by \label, so you're seeing Reference and not Reference 1.

The .aux file of that tiny OP document is tiny too:

\relax 
\newlabel{a}{{}{1}}

There is the label name a and the cross-reference information after the name, i.e. {{}{1}}. The first brace-pair inside there is empty here whereas the second one has 1 as content, this is the page number, but not the reference number as requested -- LaTeX wrote an empty \@currentlabel content to the .aux file.

Here is the relevant code from latex.ltx (lines 4089f), comments by me.

\def\label#1{\@bsphack
  \protected@write\@auxout{}%
         {\string\newlabel{#1}{{\@currentlabel}{\thepage}}}% Use `\@currentlabel`
  \@esphack}
\def\refstepcounter#1{\stepcounter{#1}%
    \protected@edef\@currentlabel
       {\csname p@#1\endcsname\csname the#1\endcsname}% Define `\@currentlabel`
}
\def\@currentlabel{}% Empty definition at the beginning. 

Assuming a standard document class like article, for example \section (not \section*) uses \refstepcounter{section} internally (actually it is \@sect that calls that macro, but let us ignore this for a moment, also the fact that secnumdepth must have the appropiate value) and following example will provide a reference:

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

\section{Foo}\label{a}
Reference \ref{a}
\end{document}

enter image description here