Understanding Linking (Part 1)

Kunal Desai
The Startup
Published in
3 min readMay 24, 2020

--

You may have wondered at some point: how does a program of multiple files access variables or functions defined in other files? That is the goal of the linker. The linker aims to take multiple pieces of code and combine them into one that can be read and understood by the computer. This has allowed us to decompose large software projects into smaller sets of libraries or modules.

In C, we usually use a compiler which preprocesses source code, compiles it, assembles it, and then links it for us. The first step in this is preprocessing source code.

Let’s look at an example for a simple program.

Preprocessing source code will process all the macros like AGE and evaluate the conditionals to output something like the following:

You can try this by running gcc -E main.c -o main.i and looking at the output.

Once the code has been preprocessed, it is given to the compiler which takes each file and turns the source code into assembly…

--

--