[Tex/LaTex] How to use subcaption with standalone

standalonesubcaption

I tried to \input in my main document file a standalone section, which uses the subcaption package. The standalone file compiles just fine. But when I try to compile the main document I get an

Undefined control sequence

error in caption3.sty.

The error is caused by the \usepackage{subcaption} alone, so it even occurs when subcaption is not actually used.

Here is a minimal working example:

main.tex:

\documentclass{scrartcl}
\usepackage[subpreambles]{standalone}
\begin{document}
  \input{subcaption_with_standalone}
\end{document}

subcaption_with_standalone.tex:

\documentclass{standalone}
\usepackage{subcaption}
\begin{document}
  This does not even use a subfigure.
\end{document}

How can I make subcaption (or something similar, preferrably not deprecated) work with standalone?

Best Answer

Several packages use the \AtBeginDocument command. When these packages are loaded in the preamble of a sub-file, these commands will never be executed.

The option subpreamples=true is thought for macros and alike, not for loading packages. If you need the package in your sub-file, you have to load it in your main file as well. Alternatively, you may just compile your sub-file with all packages you need and run the main file without the option subpreambles=true.

Loading subcaption in the main preamble works:

main.tex

% arara: lualatex
% arara: lualatex

\documentclass{scrartcl}
\usepackage[subpreambles=true]{standalone}
\usepackage{subcaption}
\usepackage{todonotes}
\usepackage{graphicx}
\begin{document}
  \input{subcaption_with_standalone}
\end{document}

subcaption_with_standalone.tex

\documentclass{standalone}
\usepackage{subcaption}
\usepackage{todonotes}
\usepackage{graphicx}
\begin{document}
\begin{figure}
\centering
    \begin{subfigure}{2in}
    \centering
    \missingfigure{Figure 1}
    \end{subfigure}
    \begin{subfigure}{2in}
    \centering
    \missingfigure{Figure 2}
    \end{subfigure}
\end{figure}
\end{document}
Related Question