[Tex/LaTex] Cross Reference problem

cross-referencingexternal filesxr

I have a problem when I use a cross-reference from other files. I have a folder in which there is a main.tex file and a subfolder (Chapter) containing Chapter1.tex and Chapter2.tex.

In the main file, I include only the chapter files like this:

    \include{Chapters/Chapter1}
    \include{Chapters/Chapter2}

My problem is that in the Chapter2.tex file I need to reference a section from Chapter1.

Chapter1.tex

\documentclass{standalone}
\begin{document}
\chapter{chapter}
\label{ch:first_chapter}

\section{first section}\label{sc:first_section}
     some Text..........
\end{document}

Chapter2.tex

\documentclass{standalone}
\usepackage{xr-hyper}
\usepackage{hyperref}
\externaldocument[C1-]{/Chapter1}
\begin{document}
\chapter{Second Chapter}
\label{ch:second_chapter}
\section{section}\label{sc:first_section_ch2}

 Some text...text \ref{C1-sc:first_section}
 \end{document}

When I compile the file, only ?? appears.

Best Answer

I don't think \chapter is defined for the standalone document class. Besides this, for me this sounds more like a job for the subfiles package then for standalone:

main.tex:

\documentclass{book}
\usepackage{subfiles}
\usepackage{xr-hyper}
\usepackage{hyperref}
\usepackage{xstring}

\begin{document}
   \subfile{chapter1}
   \subfile{chapter2}
\end{document}

and chapter1.tex

% !TeX root = chapter1.tex 
\documentclass[main]{subfiles}

\begin{document}
\chapter{chapter}
\label{ch:first_chapter}

\section{first section}\label{sc:first_section}
     some Text..........
\end{document}

and chapter2.tex

% !TeX root = chapter2.tex 
\documentclass[main]{subfiles}

\IfEq{\jobname}{\detokenize{main}}{}{%
    \externaldocument{chapter1}
}

\begin{document}
\chapter{Second Chapter}
\label{ch:second_chapter}
\section{section}\label{sc:first_section_ch2}

 Some text...text \ref{sc:first_section}
\end{document}

(the above example assumes that all 3 files are in the same folder, for the usage of subfolders, you have to adjust the paths of the main file and the chapter files accordingly)

Related Question