Why create a .a file from .o for static linking?

Viewed 17238

Consider this code:

one.c:

#include <stdio.h>

int one() {
   printf("one!\n");
   return 1;
}

two.c:

#include <stdio.h>

int two() {
   printf("two!\n");
   return 2;
}

prog.c

#include <stdio.h>

int one();
int two();

int main(int argc, char *argv[]) 
{
   one();
   two();

   return 0;
}

I want to link these programs together. So I do this:

gcc -c -o one.o one.c
gcc -c -o two.o two.c
gcc -o a.out prog.c one.o two.o

This works just fine.

Or I could create a static library:

ar rcs libone.a one.o
ar rcs libtwo.a two.o
gcc prog.c libone.a libtwo.a
gcc -L. prog.c -lone -ltwo

So my question is: why would I use the second version - the one where I created a ".a" files - rather than linking my ".o" files? They both seem to be statically linking, so is there an advantage or architectural difference in one vs another?

6 Answers

Whenever I am asked this question(by freshers in my team), "why (or sometimes even a 'what is') a .a?", I use the below answer that uses the .zip as an analogy.

"A dotAy is like a zip file of all the dotOhs which you would want to link while building your exe/lib. Savings on disk space, plus one need not type names of all dotOhs involved."

so far, this has seemed to make them understand. ;)

Related