The easiest solution in these cases is to add \protect
in front of the usual suspects; \subref
is one of them because it has a *-variant.
\documentclass{article}
\usepackage{graphicx}
\usepackage{subfig}
\begin{document}
\begin{figure}[!ht]
\centering
\subfloat[]{%
\label{subfig1}%
\includegraphics[width=.4\linewidth]{fig1.pdf}%
}%
\qquad
\subfloat[]{%
\label{subfig2}%
\includegraphics[width=.4\linewidth]{fig2.pdf}%
}
\caption{A caption for figures \protect\subref{subfig1} and \protect\subref{subfig2}.}
\label{myfig}
\end{figure}
\end{document}
Note where I added/removed %
at end of lines and the position of \label{myfig}
after \caption
.
This might be annoying if you have several appearances of \subref
in moving arguments. In this case you can “robustify” the command:
\documentclass{article}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{etoolbox} % for \robustify
\robustify{\subref}
\begin{document}
\begin{figure}[!ht]
\centering
\subfloat[]{%
\label{subfig1}%
\includegraphics[width=.4\linewidth]{fig1.pdf}%
}%
\qquad
\subfloat[]{%
\label{subfig2}%
\includegraphics[width=.4\linewidth]{fig2.pdf}%
}
\caption{A caption for figures \subref{subfig1} and \subref{subfig2}.}
\label{myfig}
\end{figure}
\end{document}
Another solution is to avoid subfig
for subcaption
, which is the path I'd recommend:
\documentclass{article}
\usepackage{graphicx}
\usepackage{subcaption}
\begin{document}
\begin{figure}[!ht]
\centering
\subcaptionbox{\label{subfig1}}{%
\includegraphics[width=.4\linewidth]{fig1.pdf}%
}%
\qquad
\subcaptionbox{\label{subfig2}}{%
\includegraphics[width=.4\linewidth]{fig2.pdf}%
}
\caption{A caption for figures \subref{subfig1} and \subref{subfig2}.}
\label{myfig}
\end{figure}
\end{document}
\subref
, i.e.\protect\subref{subfig1}
protect
are, but now I know where to begin. Thanks very much @karlkoeller!