Путь компиляции и выполнения
Введено
5:52
Основы компьютерных систем
This course follows a program from a single bit to a running process. The first two units are the alphabet: how bits encode data, and how logic gates compute…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| preprocessor/prɪˈprəʊsesə/ | Предкомпилятор |
| compiler/kəmˈpaɪlə/ | Компилятор |
| assembler/əˈsemblə/ | Ассемблер |
| object file/ˈɒbdʒekt faɪl/ | Целевой файл |
| linker/ˈlɪŋkə/ | Линковщик |
| loader/ˈləʊdə/ | Загрузчик |
| separate compilation/ˈseprət ˌkɒmpɪˈleɪʃn/ | Раздельная компиляция |
| bytecode/ˈbaɪtkəʊd/ | Байт-код |
It compiled, so why did it fail?
- A student builds a program and gets
undefined reference to 'area'. The code had no errors when it compiled, so which tool is complaining? - Turning source code into a running program takes four stages, and each stage has its own kind of error. Knowing the stages tells you where to look.
Stage 1: the preprocessor
- The preprocessor 预处理器 expands
#includeand#define. It works on plain text and producesmain.i. - Macros have no types: the preprocessor only swaps text, so a bad macro shows up as a strange error later.
Предпроцессор проверяет, что макрос используется с правильными типами данных.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Предпроцессор лишь заменяет текст. Типы проверяются позже компилятором.
Stage 2: the compiler
- The compiler 编译器 checks types and turns C into assembly language,
main.s. - Type errors and syntax errors come from this stage.
Преобразование main.i в main.s — задача —
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Предпроцессор создает .i, компилятор — .s, ассемблер — .o, а линкер формирует программу.
Stage 3: the assembler
- The assembler 汇编器 turns assembly into machine code in an object file 目标文件,
main.o. - A call to a function in another file stays unresolved: the object file just records the name it needs.
Stage 4: the linker, then the loader
- The linker 链接器 joins object files and libraries and matches each needed name to its definition. A name with no definition gives "undefined reference": a linker error, not a compiler error.
- The result is an executable. The loader 加载器 maps it into memory and starts it as a process.

Расставьте этапы сборки в правильном порядке.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Расширения файлов обозначают этапы.
Ошибка undefined-reference возникает из-за —
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Линкер сопоставляет имена в объектных файлах, поэтому отсутствие определения относится к его типу ошибок.
Соотнесите каждую ошибку с этапом, который её генерирует.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
У каждого этапа свой класс ошибок, поэтому сообщение указывает, где искать проблему.
Why keep the stages apart
- Separate compilation 分别编译: change one file in a million-line program and only that file is compiled again; then the linker joins everything.
- Libraries can ship as ready-made object files, and every error belongs to one stage: macro, type, instruction or symbol.
В проекте 40 .c файлов. Вы редактируете один из них (не заголовочный). Сколько файлов необходимо перекомпилировать перед линковкой?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
При отдельной компиляции пересобирается только измененный файл; линкер затем объединяет все 40 объектных файлов.
Compiled and interpreted
- C goes through all four stages before it runs. The result is fast but tied to one kind of machine.
- Python reads the source each run: CPython compiles it to bytecode 字节码, and a virtual machine runs that. The difference is when translation happens.
Компилируемое и интерпретируемое исполнение различаются прежде всего —
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Скомпилировать один раз и выполнять многократно, либо считывать и выполнять через виртуальную машину каждый раз.
CPython выполняет исходный код Python без этапа трансляции вообще.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
CPython сначала компилирует исходный код в байт-код, а затем его виртуальная машина выполняет этот байт-код.
Worked example: the four files
main.cbecomesmain.i(preprocess),main.s(compile),main.o(assemble), thenprog(link). Each file can be kept and inspected with the right compiler flag.- In the opening story,
areawas defined ingeom.c, but onlymain.owas linked. Linkmain.oandgeom.otogether and the error disappears.
Three common slips
- Calling every failure a compile error. "Undefined reference" comes from the linker.
- Forgetting that headers are text.
#includepastes the file in; macros have no types. - Assuming optimisation never changes float results. Some optimisations reorder float arithmetic, and rounding then changes.
Recap
- Each stage has its own output and its own errors; then the loader starts the program:
| Stage | Makes | Errors |
|---|---|---|
| Preprocessor | main.i (text) |
bad macros |
| Compiler | main.s (assembly) |
syntax, types |
| Assembler | main.o (object) |
bad instructions |
| Linker | executable | undefined reference |
- Undefined reference means a linker problem: a missing object file or library.
- Compiled or interpreted is about when translation happens: once before running, or every run.
Что пошло не так? Это увидит только команда сайта.