> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/knowledge-base/033-cross-referencing-with-the-xr-package-in-overleaf.md).

# Cross referencing with the xr package in Overleaf

## Overview

The [`xr` package](https://ctan.org/pkg/xr?lang=en) lets you create cross-references to equations, figures, tables etc. contained in external LaTeX documents, provided those documents are *standalone.* A standalone LaTeX document is one that can be compiled because it contains a `\documentclass{...}` statement and the `\begin{document}`...`\end{document}` construct.

### Usage summary

1. Write `\usepackage{xr}` in the preamble of the LaTeX file that needs to cross-reference content contained in external LaTeX files.
2. Use the `xr` package command `\externaldocument{filename}` to specify the external document(s) whose content you want to cross-reference.

The `xr` package works by using cross-reference labels contained in the `.aux` files generated when the external LaTeX documents are compiled.

### How cross-referencing works (a short summary)

To cross-reference an item in a LaTeX document you need to:

1. Give it a unique identifier, `some_string`, using the `\label` command:

```latex
\label{some_string}
```

3. At the location where you want to reference that element, you need to write

```latex
\ref{some_string}
```

To be very brief, LaTeX manages cross-referencing by writing data to a file called `filename.aux` where `filename` is the name of the main `.tex` file being compiled.

For the process to work, the LaTeX document has to be compiled at least twice: the first compilation *generates* the reference data—writing it to `filename.aux`. During the second compilation, LaTeX *reads* `filename.aux` to resolve the references, providing data to replace instances of `\ref{some_string}`.

* For more detail on cross-referencing see the Overleaf article [Cross referencing sections, equations and floats](/latex/document-structure/03-cross-referencing-sections-equations-and-floats.md).

## Projects where the xr package is not required

Large LaTeX projects, such as books or long reports, are often split into a series of smaller `.tex` files, one per chapter, with each chapter’s `.tex` file added to the main LaTeX document using `\input` or `\include`. Typically, those chapters are not standalone: you cannot compile individual chapters because they do not contain a `\documentclass{...}` statement or the `\begin{document}...\end{document}` construct. Those chapters are destined for *inclusion* into a “container” document which *can* be compiled. In those circumstances, cross-referencing to document elements—within any individual chapter file—can proceed as normal: you do not need to use the `xr` package.

To explore an example of a large project you can [open this example in Overleaf.](https://www.overleaf.com/project/new/template/20618?id=70769185\&templateName=Managing+a+large+project+on+Overleaf\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## Example of a project where the xr package is required

Suppose you have a set of standalone LaTeX documents such as a collection of N articles: `article1.tex`, `article2.tex` ... `articleN.tex`. Each of those articles can be compiled separately and it is likely they were written using a variety of document classes, packages etc.

Now imagine you want to use LaTeX to write an overview or summary of those articles—we’ll call our file `summary.tex`. Our summary needs to reference sections, figures, tables, equations etc. contained within those individual, standalone, N articles. How can we do that?

The `xr` package let’s you do this: it enables `summary.tex` to use reference labels generated by any of the standalone `article*.tex` files.

### A note on .aux files

* Note, here we are using an asterisk (`*`) as a placeholder for any number from 1 to N.

Compiling any of the standalone files `article1.tex`, `article2.tex` ... `articleN.tex` causes LaTeX to generate a corresponding `article*.aux` (\*\*`aux`\*\*illary) file which, among other items, contains label data required to generate cross-references.

If any of the `article*.tex` files are edited—for example, to change, add, or remove labels (`\label{...}`)—the corresponding `article*.tex` file(s) must be recompiled to update the associated `article*.aux` file(s).

Detecting changes to `article*.tex`, and subsequently recompiling them, can be automated on Overleaf by using a suitable `latexmkrc` file.

## How to use xr on Overleaf

We’ll use a simplified version of our multiple-article example; in particular, we show how to automate the compilation process via a `latexmkrc` file [supplied to Overleaf by John Collins](#code-for-latexmkrc) ([maintainer of `latexmk`](https://ctan.org/pkg/latexmk?lang=en)).

### Files used in our example

Our example uses the following files:

* `**summary.tex**`: this is our overview document. We need it to reference content contained in `article1.tex`, such as figures and sections.
  * `summary.tex` loads the `xr` package and uses `\externaldocument{article1}` to specify that reference data from `article1.aux` should be used.
* `**article1.tex**`: a single standalone article which contains internal cross-references. Compiling `article1.tex` generates cross-reference data contained in the file `article1.aux`.
  * An external file such as `article1.tex` that might have been written by someone else—for you to use “as supplied,” i.e., untouched.
* `**latexmkrc**`: contains code (Perl) to automate recompilation of `article1.tex` due to any changes made to it—to create an updated `article1.aux` file.
  * Our `latexmkrc` file was [supplied to Overleaf by John Collins](#code-for-latexmkrc) ([maintainer of `latexmk`](https://ctan.org/pkg/latexmk?lang=en)).

### About the \externaldocument command

The `xr` package provides the`\externaldocument` command, which has the general form

```latex
\externaldocument[prefix]{external_file}
```

* **`prefix` (optional):** This optional argument allows you to define a prefix that will be added to all the labels imported from the external document. This is useful to avoid conflicts if the same label names are used in multiple documents.
* **`external_file` (required):** This required argument specifies the name of the external LaTeX document (without the `.tex` extension) from which you want to import references. The `xr` package will look for the `.aux` file corresponding to `external_file` (e.g., `external_file.aux`) to retrieve the labels.

By way of example, if our main `.tex` file `summary.tex` and the external file, `article1.tex` both contain the label `\label{eq:1}` then we have a label name clash. That clash can be prevented by writing

```latex
\externaldocument[art1-]{article1}
```

in which case all labels created by compiling `article1.tex` are prefixed by `art1-`. Now you can access `\label{eq:1}`, contained in `article1.tex`, by writing `\ref{art1-eq:1}` in `summary.tex`.

### The project files

#### article1.tex

The following code can be opened in Overleaf using the link below the listing.

```latex
\documentclass{article}
\title{This is \texttt{article1.tex}}
\begin{document}
\section{Introduction}
\label{introduction}

This is a standalone \LaTeX{} document with
references we want to use in \texttt{summary.tex}.

\subsection{Math references}
\label{mathrefs}
As mentioned in section \ref{introduction},
different elements can be referenced within
a document.

\subsection{Powers series}
\label{powers}

\begin{equation}
\label{eq:1}
\sum_{i=0}^{\infty} a_i x^i
\end{equation}

Equation \ref{eq:1} is a typical power series.
\end{document}
```

[Open `article1.tex` in Overleaf](https://www.overleaf.com/docs?engine=%5B%5B%3ATemplate%3AEngine%5D%5D}\&snip_name\[]=readme.txt\&snip\[]=A+project+created+from+the+Overleaf+wiki\&snip_name\[]=article1.tex\&main_document=article1.tex\&snip\[]=%5Cdocumentclass%7Barticle%7D%0A%5Ctitle%7BThis+is+%5Ctexttt%7Barticle1.tex%7D%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BIntroduction%7D%0A%5Clabel%7Bintroduction%7D%0A%0AThis+is+a+standalone+%5CLaTeX%7B%7D+document+with%0Areferences+we+want+to+use+in+%5Ctexttt%7Bsummary.tex%7D.%0A%0A%5Csubsection%7BMath+references%7D%0A%5Clabel%7Bmathrefs%7D%0AAs+mentioned+in+section+%5Cref%7Bintroduction%7D%2C+%0Adifferent+elements+can+be+referenced+within%0Aa+document.%0A%0A%5Csubsection%7BPowers+series%7D%0A%5Clabel%7Bpowers%7D%0A%0A%5Cbegin%7Bequation%7D%0A%5Clabel%7Beq%3A1%7D%0A%5Csum_%7Bi%3D0%7D%5E%7B%5Cinfty%7D+a_i+x%5Ei%0A%5Cend%7Bequation%7D%0A%0AEquation+%5Cref%7Beq%3A1%7D+is+a+typical+power+series.%0A%5Cend%7Bdocument)

Compiling `article1.tex` produces the following output:

![Output produced by compiling article1.tex file on Overleaf](/files/b3Hd0Gkk7CiglHgwNmZW)

#### summary.tex

Here is our initial `summary.tex` file *before* we have specified which external document we want to reference. For simplicity, `summary.tex` does not contain any `\label` commands because there are no internal cross-references. All `\ref` commands refer to labels generated by `\label` commands contained in `article1.tex`.

```latex
\documentclass{article}
\usepackage{xr}
\title{This is \texttt{summary.tex}}
\begin{document}
In the file \texttt{article1.tex}, the introduction is section \ref{introduction}.  In that file, there are two subsections: \ref{mathrefs} and \ref{powers}. In subsection \ref{powers}, equation \ref{eq:1} demonstrates a power series.
\end{document}
```

[Open this *incomplete* `summary.tex` in Overleaf](https://www.overleaf.com/docs?engine=%5B%5B%3ATemplate%3AEngine%5D%5D}\&snip_name\[]=readme.txt\&snip\[]=A+project+created+from+the+Overleaf+wiki\&snip_name\[]=summary.tex\&main_document=summary.tex\&snip\[]=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bxr%7D%0A%5Ctitle%7BThis+is+%5Ctexttt%7Bsummary.tex%7D%7D%0A%5Cbegin%7Bdocument%7D%0AIn+the+file+%5Ctexttt%7Barticle1.tex%7D%2C+the+introduction+is+section+%5Cref%7Bintroduction%7D.++In+that+file%2C+there+are+two+subsections%3A+%5Cref%7Bmathrefs%7D+and+%5Cref%7Bpowers%7D.+In+subsection+%5Cref%7Bpowers%7D%2C+equation+%5Cref%7Beq%3A1%7D+demonstrates+a+power+series.%0A%5Cend%7Bdocument%7D)

If we compile this version of `summary.tex` it will attempt to read reference data from `summary.aux` but the required data is contained in the external file `article1.aux` which cannot, yet, be accessed.

Compiling this incomplete `summary.tex` file produces the following output, with double question marks showing undefined references:

![Image showing reporting missing references](/files/uVxj1FJc2xcrDpbEFHS5)

### Specifying the external document

The next step is to specify `article1` as the name of the external document whose labels we want to reference. Add the following line to the preamble of `summary.tex`:

```latex
\externaldocument{article1}
```

Here, `article1` can be replaced by any file whose labels you want to access—you can use multiple `\externaldocument` commands to access additional external files.

### Creating the latexmkrc file

The next step is to create a `latexmkrc` file as shown below:

* In your project editor window, select the **New File** icon at the top-left of the project window.
* Select **New File** from within the **Add Files** pop-up dialog box and name the file `latexmkrc`—note there is no file extension:

![Creating a latexmkrc file in Overleaf](/files/wLOKFMu0PQtrevEZpJMN)

* Make sure that the `latexmkrc` file created and saved in the top (root) level of the project’s files area. That is, not inside any folders in the file tree.
* Copy and paste the following code into your `latexmkrc` file.

#### Code for latexmkrc

Overleaf are grateful to John Collins, [maintainer of `latexmk`](https://ctan.org/pkg/latexmk?lang=en), for contacting us to supply the following `latexmkrc` file, which we are delighted to publish in full—including the extremely helpful inline comments.

```perl
# This shows how to use the xr package with latexmk.
# John Collins 2023-03-29
#
# The xr package ("a system for eXternal References") is used by a document
# to make references to sections, equations, etc in other external
# documents.
# The definitions in this file enable latexmk to apply latexmk to
# automatically update an external document whenever its .tex file changes,
# so that the references in the main document stay up to date.

# Notes:
#    1. This version is defined to put the files from the compilations of
#       the external documents into a defined subdirectory, to segregate
#       potentially many generated files from the main document
#       directories.
#    2. But for latexmk's custom dependency mechanism to be used, as here,
#       the aux file from compilation of a subdocument must be generated in
#       the same directory as the corresponding source .tex file.  So the
#       .aux file is copied.
#    3. It is assumed that the external documents are to be compiled by
#       pdflatex.  This can be changed, of course, by changing the '-pdf'
#       option given to the invoked latexmk to whatever is needed.
#    4. An ideal implementation would also ensure that recompilation of an
#       external document also happens whenever any of its other source
#       files changes.  But this is not done in the present version, and
#       would probably entail either the use of internal latexmk variables
#       or extra enhancements to latexmk.
#    5. The code uses subroutines copy and fileparse that are loaded by
#       latexmk from the Perl packages File::Copy and File::Basename.
#    6. It also uses some not-yet-documented features of latexmk: an array
#       variable @file_not_found and subroutines popd, pushd, and
#       rdb_add_generated.

#--------------------
# Configurable choices for compilation of external documents

# Subdirectory for output files from compilation of external documents:
$sub_doc_output = 'output-subdoc';

# Options to supply to latexmk for compilation of external documents:
@sub_doc_options = ();

push @sub_doc_options, '-pdf'; # Use pdflatex for compilation of external documents.
# Replace '-pdf' by '-pdfdvi', 'pdfxe', or 'pdflua' if needed.

#--------------------

# Add a pattern for xr's log-file message about missing files to latexmk's
# list.  Latexmk's variable @file_not_found is not yet documented.
# This line isn't necessary for v. 4.80 or later of latexmk.
push @file_not_found, '^No file\\s*(.+)\s*$';

add_cus_dep( 'tex', 'aux', 0, 'makeexternaldocument' );
sub makeexternaldocument {
    if ( $root_filename ne $_[0] )  {
        my ($base_name, $path) = fileparse( $_[0] );
        pushd $path;
        my $return = system "latexmk",
                            @sub_doc_options,
                            "-aux-directory=$sub_doc_output",
                            "-output-directory=$sub_doc_output",
                            $base_name;
        if ( ($sub_doc_output ne '') && ($sub_doc_output ne '.') ) {
               # In this case, .aux file generated by pdflatex isn't in same
               # directory as the .tex file.
               # Therefore:
               # 1. Actual generated aux file must be listed as produced by this
               #    rule, so that latexmk deals with dependencies correctly.
               #    (Problem to overcome: If $sub_dir_output is same as $aux_dir
               #    for the main document, xr may read the .aux file in the
               #    aux_dir rather than the one the cus dep is assumed by latexmk
               #    to produce, which is in the same directory as the .tex source
               #    file for this custom dependency.)
               #    Use not-yet-documented latexmk subroutine rdb_add_generated
               #    to do this:
               # 2. A copy of the .aux file must be in same directory as .tex file
               #    to satisfy latexmk's definition of a custom dependency.
             rdb_add_generated( "$sub_doc_output/$base_name.aux" );
             copy "$sub_doc_output/$base_name.aux", ".";
        }
        popd;
        return $return;
   }
}
```

### Open an Overleaf project demonstrating xr

The following three-file project can now be opened in Overleaf using the links provided above and below the file listings. Note that the `latexmkrc` file contains the code supplied by John Collins but, for brevity, most of the comments have been removed.

[Open this three-file example in Overleaf.](/latex/knowledge-base/033-cross-referencing-with-the-xr-package-in-overleaf.md)

**summary.tex**

This is our summary file. From within this file we want to use cross-references created in external files. Here, we want to use labels generated in `article1.tex`.

```latex
\documentclass[12pt]{article}
\usepackage{xr}

\title{Using the xr package on Overleaf}
% put all the external documents here!
\externaldocument{article1}

\begin{document}

In the file \texttt{article1.tex}, the introduction is section \ref{introduction}.  In that file, there are two subsections: \ref{mathrefs} and \ref{powers}. In subsection \ref{powers}, equation \ref{eq:1} demonstrates a power series.

\end{document}
```

**article1.tex**

This file is one of our articles. Note how it contains various `\label` commands to create labels that, thanks to the `xr` package, we can use in the file `summary.tex`.

```latex
\documentclass{article}
\title{This is \texttt{article1.tex}}
\begin{document}
\section{Introduction}
\label{introduction}

This is a standalone \LaTeX{} document with
references we want to use in \texttt{summary.tex}.

\subsection{Math references}
\label{mathrefs}
As mentioned in section \ref{introduction},
different elements can be referenced within
a document.

\subsection{Powers series}
\label{powers}

\begin{equation}
\label{eq:1}
\sum_{i=0}^{\infty} a_i x^i
\end{equation}

Equation \ref{eq:1} is a typical power series.
\end{document}
```

**latexmkrc**

This `latexmkrc` file contains code to ensure the external files are compiled.

```latex
$sub_doc_output = 'output-subdoc';

@sub_doc_options = ();

push @sub_doc_options, '-pdf'; # Use pdflatex for compilation of external documents.
# Replace '-pdf' by '-pdfdvi', 'pdfxe', or 'pdflua' if needed.

push @file_not_found, '^No file\\s*(.+)\s*$';

add_cus_dep( 'tex', 'aux', 0, 'makeexternaldocument' );
sub makeexternaldocument {
    if ( $root_filename ne $_[0] )  {
        my ($base_name, $path) = fileparse( $_[0] );
        pushd $path;
        my $return = system "latexmk",
                            @sub_doc_options,
                            "-aux-directory=$sub_doc_output",
                            "-output-directory=$sub_doc_output",
                            $base_name;
        if ( ($sub_doc_output ne '') && ($sub_doc_output ne '.') ) {

             rdb_add_generated( "$sub_doc_output/$base_name.aux" );
             copy "$sub_doc_output/$base_name.aux", ".";
        }
        popd;
        return $return;
   }
}
```

[Open this three-file example in Overleaf.](/latex/knowledge-base/033-cross-referencing-with-the-xr-package-in-overleaf.md)

The following graphic is an annotated version of the output from typesetting `summary.tex`, showing the cross-references and the corresponding labels from the external file `article1.tex`.

![Showing references imported from an external file](/files/6S95OFqM3Mu71ytbqUcB)

* For more detail on cross-referencing see the Overleaf article [Cross referencing sections, equations and floats](/latex/document-structure/03-cross-referencing-sections-equations-and-floats.md).

## A note about syntax errors

For your main project file, you can use Overleaf’s [Stop on First Error compilation mode](/latex/knowledge-base/149-using-the-stop-on-first-error-compilation-mode.md) to ensure compilation terminates immediately upon detection of the first error. This can help isolate and identify errors in your code, rather than allowing errors to cascade which makes it far more difficult to find and debug problems.

The *external* documents are compiled automatically via the `latexmkrc` file; consequently, any LaTeX syntax errors within them won’t show in the Overleaf interface—unless you recompile them in Overleaf too. Errors in those external files could prevent cross-references from appearing correctly in the typeset PDF file, so we strongly recommend checking and correcting any such errors as soon as they occur.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/knowledge-base/033-cross-referencing-with-the-xr-package-in-overleaf.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
