[Tex/LaTex] Problem referencing/labeling while using the subfiles package

labelspackagessubfiles

I have a problem using labels together with the subfiles package. When I'm writing in one section and I try to reference to different section (or for that matter anything within that section) I get an undefined label error. My main.tex:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{graphicx}
\graphicspath{{images/}{../images/}}

\usepackage{subfiles}

\begin{document}
\maketitle

\section{Introduction}
\label{sec:intro}
\subfile{sections/CH1_Introduction}

\section{Theory of Ultrasound Anemometer}
\label{sec:theory}
\subfile{sections/CH2_Theory}

Then, for example, when I write in my 'introduction' section file:

In section \ref{sec:theory} the theory will be discussed ...

Which results in an undefined reference error. Can someone help me? Is the problem of the label command? Or am I doing something else wrong?

Best Answer

This can be done with the package xr. Here is an MWE that makes some assumptions about the layout of the project. In the root folder, under a file called main.tex:

\documentclass{article}
\usepackage{xr}
\usepackage{subfiles}

\begin{document}
\section{Introduction}
\subfile{sections/CH1_Introduction}
\label{sec:intro}

\section{Theory of Ultrasound Anemometer}
\subfile{sections/CH2_Theory}
\label{sec:theory}
\end{document}

Then, in a subfolder called sections, there are two additional tex files called CH1_Introduction:

\documentclass[../main.tex]{subfiles}
\externaldocument{../main.tex}

\begin{document}
This is a text written in the introduction file that discusses the rest of the paper. We will discuss the theory of ultrasound traducers in section \ref{sec:theory}.
\end{document}

and CH2_Theory.tex:

\documentclass[../main.tex]{subfiles}
\externaldocument{../main.tex}
\begin{document}
Here we talk about the ultrasound traducers that we said we would discuss in section \ref{sec:intro}. 
\end{document}

compiling main.tex than returns:

enter image description here

Now assuming that all your sections are called in the main document this should allow you to cite the sections (but not subsections with the current layout) from the introduction.