[Tex/LaTex] latex thinks reference is undefined

cross-referencingfloatsmulticol

I know that very similar questions have been asked before, but the solutions do not work.
I have the following latex code;

\documentclass[a4paper,10pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{enumerate}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
blahblah in figure\ref{diagram1}.

\begin{figure}[H]
\centering
\includegraphics[width=1\textwidth]{images/diagram.png}
\caption{blahblahblah }
\label{diagram1}
\end{figure}

\end{multicols}

\end{document}

and I obtain the following error message;

Reference `diagram1' on page 2 undefined

No matter how many times I attempt to recompile the document using pdf latex, I obtain the same error.

Has anyone here encountered this before? Where latex is clearly wrong, but you do not comprehend how/why?

Best Answer

LaTeX already told you the reason:

Package multicol Warning: Floats and marginpars not allowed inside `multicols' environment!.

And the entire float object is gone including the \label. Therefore the reference is undefined.

Also H is not supported causing an error, which is fixed by adding package float. If you don't want a floating object, then there are other means to add a caption, see the following example.

Also if there are two columns, then there is no place for an image with width of the whole \textwidth. \linewidth is better, because it reflects the current line width.

\documentclass[a4paper,10pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{enumerate}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
blahblah in figure\ref{diagram1}.

\noindent
\begin{minipage}{\linewidth}
  \centering
  \includegraphics[width=\linewidth]{images/diagram.png}
  \captionof{figure}{blahblahblah }
  \label{diagram1}
\end{minipage}

\end{multicols}
\end{document}

Result

If you want to have a figure across the full text width, then figure* instead of figure can be used, but only as floating object without H:

\documentclass[a4paper,10pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[demo]{graphicx}
\usepackage{enumerate}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
blahblah in figure\ref{diagram1}.

\begin{figure*}
\includegraphics[width=\linewidth]{images/diagram.png}
\caption{blahblahblah }
\label{diagram1}
\end{figure*}

\end{multicols}
\end{document}