Stage 1 · Foundations 2 / 48 ≈ 9 min read

How to Compile LaTeX: Engines, Editors and latexmk

A LaTeX source file is plain text. Nothing happens until an engine reads it, runs it through TeX and writes a PDF. This lesson covers that loop end to end: what to install, which engine to pick, how to compile from a terminal at least once so you know what your editor is doing, and how to read the output when it fails.

    Three programs, not one

    Beginners talk about "LaTeX" as if it were an application like Word. It is a stack of three separate pieces, and knowing which one is failing halves your debugging time.

    The distribution is the bundle you install: TeX Live (Linux, Windows, macOS) or MacTeX (the macOS packaging of TeX Live). It ships the TeX engine, the fonts, thousands of packages and the command-line tools. MiKTeX is the alternative Windows-first distribution; it installs missing packages on demand, which is convenient locally and a source of unreproducible builds on someone else's machine.

    The engine is the program that actually reads your .tex file: pdflatex, xelatex or lualatex. They differ in font technology and Unicode handling, covered below.

    The editor is where you type: Overleaf in the browser, VS Code with the LaTeX Workshop extension, TeXstudio, Kile, Emacs with AUCTeX. The editor only ever calls an engine for you. It has no magic of its own, which is exactly why you should run the command line once.

    A LaTeX stack: distribution, engine, editor — and the PDF they produce 1 · Distribution TeX Live / MacTeX / MiKTeX Everything you install once: engines · fonts · 3 500+ packages tlmgr install tikz 2 · Engine pdflatex · xelatex · lualatex Reads the .tex, writes the PDF. Fonts and Unicode decide the choice: pdf = classic · xe/lu = system fonts 3 · Editor Overleaf · VS Code · TeXstudio Only a front-end: it calls an engine. Install one of these without a distribution and nothing compiles. What the run produces thesis.tex + latexmk -pdf thesis.pdf the only file you keep and open build products .aux .log .toc .out .bbl .synctex.gz regenerate them, never hand-edit them — latexmk -c clears them the .log is where failures are explained read the first line starting with ! not the last one on screen
    Three separate things in one stack: the distribution is what you install, the engine is what runs, the editor is what you type into.

    pdflatex, xelatex or lualatex: choosing an engine

    pdflatex is the default and the fastest. It writes PDF directly, and it is the only engine some older packages still support. Its limitation is font handling: it uses Type 1 and METAFONT fonts described by .fd files, so system TrueType or OpenType fonts are awkward, and input is expected in 8-bit encodings, which is why accented characters historically needed \'e rather than é.

    xelatex uses the fontspec layer and talks to the operating system font machinery. Any font you can install, you can use, and the input is UTF-8, so you type é, π or 漢字 directly. It is the usual choice for non-Latin scripts and for documents with a custom typeface.

    lualatex also does Unicode and system fonts, and additionally embeds a Lua interpreter so your document can run code — useful for programmatically generated tables or complex line-breaking logic. It is the slowest of the three and needs a two-pass run to write its .run.xml back into the document.

    Rule of thumb: start with pdflatex; switch to xelatex the moment you need a system font or a non-Latin script; reach for lualatex only when you have a concrete reason. Whichever you pick, the same source normally compiles under the others, so the decision is cheap to revisit.

    E = mc^{2}
    E = mc^{2}

    The sixty-second document

    Save this as test.tex. It is the smallest file that exercises the things every later lesson assumes: a class, an encoding, two packages, a title block and a display equation.

    \documentclass[12pt,a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath,amssymb}
    
    \title{Ohm's law}
    \author{A. Student}
    \date{\today}
    
    \begin{document}
    \maketitle
    
    The current through a resistor is
    \[
      I = \frac{U}{R}.
    \]
    
    \end{document}

    Compiling from the command line, once, properly

    Editors hide this, but you should run it by hand at least once so that "it does not compile" becomes a diagnosable statement instead of a mood.

    A plain pdflatex test.tex run stops at every error and waits for keyboard input, which is why batch runs pass -interaction=nonstopmode: the run continues, writes what it managed, and leaves the errors in the log.

    Cross-references and the table of contents need more than one pass. The first run discovers a \label and writes a placeholder into test.aux; the second run reads that file and fills in the real number; a third is needed when the resolved numbers change page breaks and therefore the page numbers themselves. Doing this by hand is tedious and easy to get wrong:

    Why LaTeX needs more than one pass: labels written to .aux on pass one are read back on pass two PASS 1 PASS 2 PASS 3 OUTPUT thesis.tex sees \ref{eq:kirchhoff} → (??) on the page .aux + .log labels and citations are written down as they are found numbers resolved \ref now prints (4.2) — but the longer text can move a page break thesis.pdf stable page numbers + TOC still changing? run it again — that is what latexmk decides for you latexmk -pdf thesis.tex one command: picks the engine, reruns until nothing changes, runs bibtex when the .aux asks for it latexmk -pvc -pdf thesis.tex watch mode: rebuilds on every save, which is what your editor's "auto-build" button is doing underneath
    A label cannot know its own number the first time it is seen, so the run has to be repeated until the document stops changing.
    pdflatex -interaction=nonstopmode thesis.tex   # 第一遍:写出 .aux
    bibtex   thesis                                # 生成 .bbl(有文献时)
    pdflatex -interaction=nonstopmode thesis.tex   # 第二遍:吸收 .aux
    pdflatex -interaction=nonstopmode thesis.tex   # 第三遍:页码与引用收敛

    latexmk: the build tool you actually want

    latexmk is a Make-style driver shipped with both TeX Live and MacTeX. It reads the dependency list the engine writes, works out whether the bibliography, the index or a second pass is needed, and reruns until the document stops changing.

    Day to day you type one command: latexmk -pdf thesis.tex, or latexmk -xelatex thesis.tex to pick the engine. latexmk -pvc -pdf thesis.tex keeps watching the files and rebuilds on every save, which is the cheap version of an editor's auto-build. latexmk -c removes the intermediates and latexmk -C also removes the PDF.

    Put the recurring options in a .latexmkrc so your editor, your terminal and your CI all agree on what "build this" means:

    # .latexmkrc —— 放到项目根目录,之后只需要敲一次 latexmk
    $pdf_mode             = 1;      # 1 = pdflatex, 5 = lualatex, 4 = xelatex
    $pdflatex             = 'pdflatex -interaction=nonstopmode -synctex=1 %O %S';
    $bibtex_use           = 2;      # 需要时重跑参考文献
    $clean_ext            = 'synctex.gz bbl run.xml';
    $max_repeat           = 2;      # 交叉引用收敛所需的最多轮数

    What a run leaves behind, and what to keep

    After a compile a project directory is full of files you did not create by hand. Knowing which matter stops you committing junk or deleting something load-bearing.

    .log is the transcript of the run and the first place to look on failure. .aux holds the resolved labels and citations for the next pass. .toc, .lof, .lot are the collected headings and captions. .bbl is the formatted bibliography — the one intermediate worth committing when a venue freezes your source. .out carries the bookmark list produced by hyperref. .synctex.gz enables jump-from-PDF-to-source and is regenerated on demand.

    Keep the source, the images and the .bib. Everything else is a build product: latexmk -c clears it, and a .gitignore that lists these extensions keeps the repository honest.

    Reading the log when it fails

    TeX reports the first error and then keeps going, so the cascade below it is usually noise. Fix the top one and re-run before touching anything else.

    An error line starts with !, and the line number printed after it is the line where TeX noticed the problem, not necessarily where you made it — an unclosed brace three lines earlier is a classic example. The <argument> and <recently read> markers show what was being expanded.

    Three messages that are not errors: Overfull \hbox means a line is too wide for the column, so material sticks into the margin; Underfull \hbox means a line was stretched to fill; LaTeX Warning: There were undefined references means you need another pass. Overfull boxes are cosmetic and by far the most common warning in a maths document with long displayed equations.

    If the run aborts with Emergency stop, scroll up: the real message is above it. Adding -interaction=nonstopmode keeps the process from waiting on a keyboard you are not looking at.

    \mathbb{R} \setminus \mathbb{Q}
    \mathbb{R} \setminus \mathbb{Q}
    The set-minus symbol above comes from amssymb; a missing package is the most common cause of Undefined control sequence.

    Where to write: Overleaf, VS Code or a local editor

    Overleaf needs no installation, compiles on a server with a pinned TeX Live version, and shares by URL. It is the right answer for coursework, collaboration and for your first week. Its limits are compile time on large documents and the fact that you cannot always see the log line you need.

    VS Code + LaTeX Workshop gives you local speed, real search, git integration and latexmk wired to a save hook; you supply the distribution. TeXstudio is the same idea with LaTeX-specific buttons and a built-in PDF preview, and it is friendlier if you never want to touch a config file.

    The practical advice: start in Overleaf so nothing stands between you and a compiled page, move to a local editor when you want version control, faster rebuilds or your own fonts — and keep one terminal command that builds the project without any editor open, because that is the command your collaborator, your university's submission system and your CI will need.

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \documentclass[12pt,a4paper]{article}
    pdflatex -interaction=nonstopmode thesis.tex # 第一遍:写出 .aux
    # .latexmkrc —— 放到项目根目录,之后只需要敲一次 latexmk
    \mathbb{R} \setminus \mathbb{Q}

    Common mistakes

    • Installing an editor and expecting LaTeX to work. Editors are front-ends; the distribution (TeX Live, MacTeX or MiKTeX) is what provides the engine.
    • Judging a build by the last message in the log instead of the first. TeX reports one error and then misbehaves everywhere downstream of it.
    • Compiling once and concluding that cross-references are broken. Labels resolve on the second pass; use latexmk and stop counting runs by hand.
    • Committing the whole build directory. The PDF and the .aux/.log/.toc set are products, not sources.
    • Switching to xelatex to fix a font problem while keeping inputenc/fontenc from the pdfTeX setup — the old 8-bit encoding layer is what you are trying to leave behind.

    Questions about this lesson

    Do I need to install anything to use LaTeX?
    No, not if you work in Overleaf: the compiler runs on their server. Locally you need a distribution — TeX Live on Windows and Linux, MacTeX on macOS — and an editor on top of it. The editor without the distribution gives you nothing but a text box.
    What is the difference between pdflatex, xelatex and lualatex?
    All three read the same source and write a PDF. pdflatex is fastest and uses classic TeX fonts with 8-bit encodings; xelatex adds system fonts and direct Unicode input through fontspec; lualatex adds the same plus an embedded Lua interpreter for scripting your document. Start with pdflatex and move to xelatex when you need a font or a non-Latin script.
    Why does LaTeX have to compile twice?
    Because the first pass cannot know what the second pass will produce. Labels, page numbers and the table of contents are written to the .aux file while they are discovered and read back on the next run, which can itself shift page breaks. latexmk detects when the output stops changing and reruns exactly as many times as needed.
    What is latexmk and should I use it?
    latexmk is a build tool that ships with TeX Live and MacTeX. It works out which engine, which bibliography step and how many passes your document needs, then runs them. If you compile anything more than once a day, use it, and keep the options in a .latexmkrc so your editor and your terminal agree.
    How do I read a LaTeX error message?
    Open the .log and find the first line starting with an exclamation mark. The number after it is where TeX noticed the problem, which is often a line or two after where you caused it. Fix that one error, recompile, and only then look at what remains.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.