12.12 – External linkage in Linux

by subbu on December 25, 2013

If we want to develop any big application, then we divide different sections of application into different C files and then link their object files to build a single executable file.
Here each section is a .c file called module, linking them to make an executable file is called external linkage

Now we will see how external linkage is done in Linux with an example
Here in this example we will see, defining different functions in different files and using all of them in another file, compiling and linking all together

Step 1: Create function libraries and save them with .c extension

Defining a function add() in a file “one.c”, that takes two integers and returns sum of them

$gedit one.c
int add(int x,int y)
  return x+y;

Select Save (Alt+S), Quit (Q)

Defining a function sub() in a file “two.c”, that takes two integers and returns subtraction of them

$gedit two.c
int sub(int x,int y)
  return x-y;

Select Save (Alt+S), Quit (Q)

Writing a program in a file “main.c”, that uses both the functions add() and sub() defined in “one.c”, “two.c”

$gedit main.c
int main()
int a,b,sm,sb;
printf("Enter two integers:\n");
printf("Sum of two numbers %d",sm);
printf("\nSubtraction of two numbers %d",sb);
return 0;

Select Save (Alt+S), Quit (Q)

Step 2: We can compile and link all the files and generate a single executable file using gcc compiler. Here we may give the files in any order but, the gcc generates executable file (.out)

$gcc –o main main.c one.c two.c

Enter two integers:
Sum of two numbers 22
Subtraction of two numbers 2

Previous post:

Next post: