[Tex/LaTex] \usepackage{caption} breaks references to tables

captionscross-referencinglistingstables

I'm formatting the listings captions as follows:

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

However, I realized that just writting \usepackage{caption} breaks references to tables, causing warnings like:

LaTeX Warning: Reference `table:swtp' on page 13 undefined on input line 44.

and LaTeX writes "Table. ??" in the generated document.

This an example that gives me the problem:

\documentclass[10pt,letterpaper]{report}
\usepackage{caption}
\begin{document}

\chapter{Chapter}

See the Table ~\ref{table:example}

\begin{table}[htdp] 
\begin{center}
    \begin{tabular}{ | c | c |}
    \hline
    A & B  \\ \hline
    1 & 2 \\ 
    \hline
    \end{tabular}
    \caption{my cap}
\end{center}
  \label{table:example}
\end{table}

\end{document}

Best Answer

With

\begin{table}[htdp] 
\begin{center}
    \begin{tabular}{ | c | c |}
    \hline
    A & B  \\ \hline
    1 & 2 \\ 
    \hline
    \end{tabular}
    \caption{my cap}
\end{center}
  \label{table:example}
\end{table}

the label is defined when the center environment has already been closed and the object which the reference should be attached to has been forgotten.

Never use the center environment inside figure or table:

\begin{table}[htbp] 
\centering
    \begin{tabular}{ | c | c |}
    \hline
    A & B  \\ \hline
    1 & 2 \\ 
    \hline
    \end{tabular}
    \caption{my cap}\label{table:example}
\end{table}

Notice also that d is not among the possible float specifiers and probably you were meaning b (bottom).