# xr package + latexmkrc not working with includegraphics command?

I am trying to implement the trick described here for using the xr package to have latex references work across multiple files automatically. The technique works great, except if there is an includegraphics command in the file being referenced. You can see my minimal non-working exmaple here: https://www.sharelatex.com/project/594816fa8920e4376fb8d7a6. Specifically, I have

File1

\documentclass{article}

%%% HELPER CODE FOR DEALING WITH EXTERNAL REFERENCES
\usepackage{xr}
\makeatletter
\typeout{(#1)}
\IfFileExists{#1}{}{\typeout{No file #1.}}
}
\makeatother

\newcommand*{\myexternaldocument}[1]{
\externaldocument[S]{#1}
}
%%% END HELPER CODE

% put all the external documents here!
\myexternaldocument{File2}

% just to see what's happening
\listfiles

\begin{document}

We would like to reference section \ref{Spicture} of file2.tex
\end{document}


File2

\documentclass{article}
\usepackage{graphicx}

\begin{document}

\section{Label1}
\label{picture}

This section is referenced by File1.

\begin{figure}
\centering
\includegraphics{{IMG}.png}
\caption{Caption}
\end{figure}

\end{document}


.latexmkrc

add_cus_dep( 'tex', 'aux', 0, 'makeexternaldocument' );

sub makeexternaldocument {
# if the dependency isn't one of the files that this latexmk run will consider, process it
# without this test, we would get an infinite loop!
if (!($root_filename eq$_[0]))
{
system( "latexmk \"\$_[0]\"" );
}
}


When I comment out the includegraphics command in file2 and then compile file1, the reference works great. But when I uncomment the includegraphics command, the reference from file1 to file2 is broken.

Any suggestions?

• I do not understand what you are trying to do here? How exactly are labels from a different file related to gfx? – daleif Aug 15 '17 at 22:00
• Diagnostics: what does 'is broken' mean? What happens? What is on the console or in the logs? Does it work if you compile without latexmk? Are you doing this on ShareLaTeX or locally? If the former, does it work locally? – cfr Aug 16 '17 at 3:50
• This site will not let me comment without sufficient "reputation" so I will frame this as an answer, though it's not a real fix. I can confirm this issue and have been informed by ShareLatex technical support that they are looking into a fix. I can also confirm that this problem is related to latexmk and not the linking itself, as compilation using PdfLaTeX in TexMaker with the same example (minus the latexmk part) works fine. As a workaround, you should be able to compile your document by running PdfLaTeX on the main .tex file on another computer (i.e. don't rely on ShareLatex server). Anothe – Ryan Morin Aug 29 '17 at 15:30
• Your example works fine on a local installation of texlive2017 – user36296 Aug 29 '17 at 15:41