Compiling and Linking on C Programming

wahyu eko hadi saputro
4 min readOct 17, 2022

--

Hi, at this article I will continue writing around C programming, and on this occasion, I will discuss the important thing on C programming namely compiling and linking. The word compile means changing the representation of thing, and because we are talking about C, so compile means changing representation of source code from .c files into .o files. Changing representation in real life is like changing color of a wall from white painting to green painting, changing facial expression from an angry face to smiling face etc.

List of requirement :

Some term in process of creating binary file on C :

  • Source code : source code is instruction in C programming language, and the file has c extension
  • Compiler : compiler is a program from C library that can change the representation of source code that we write
  • Object code : result of compiling process, the file has .o extension
  • Linker : The job of the linker is to link together a bunch of object files (.o files) into a binary executable.

Process of creating binary or executable file on C

The role of the linker is to bring together these three elements — your object code, the standard startup code for your system, and the library code — and put them together into a single file, the executable file.

Save copy of compiled source code

If you tell the compiler to save the object code it generates into a file, it shouldn’t need to recreate it unless the source code changes. If a file does change, you can recreate the object code for that one file and then pass the whole set of object files to the compiler so they can be linked

If you change a single file, you will have to recreate the object code file from it, but you won’t need to create the object code for any other file. Then you can pass all the object code files to the linker and create a new version of the program.

A. Syntax of compiling c into object (.o) file:

example :

a. create hello-world.c

syntax of hello-world.c

b. run : gcc -c hello-world.c and the result is hello-world.o

B. Link the .o file into a binary / executable file.

Example :

a. Create some source code file :

main.c file
employee-interface.h file
employee-impl.c

b. Compile the source code :

gcc -c main.c employee-impl.c

The result are : main.o and employee-impl.o

c. Link the object file to create executable file / binary file :

gcc -o resultProgram main.o employee-impl.o

d. Run the executable file

.\resultProgram.exe

Source : Head First C — David Griffiths, Dawn Griffiths.

https://riptutorial.com/c/example/3250/calling-a-function-from-another-c-file

--

--