Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 560
poundifdef Avatar asked Dec 05 '09 18:12

poundifdef


People also ask

What is the difference between .a and .o files?

The . a file type is an "archive" library. It contains one or more .o files and it is typically used to for creating static executable files.

What is the purpose of .a file in C++?

. a files are archives. They are groups of objects or static libraries and are also input into the linker.

Why do we use static links?

Static linking increases the file size of your program, and it may increase the code size in memory if other applications, or other copies of your application, are running on the system. This option forces the linker to place the library procedures your program references into the program's object file.


1 Answers

Typically libraries are collections of object files that can be used in multiple programs.

In your example there is no advantage, but you might have done:

ar rcs liboneandtwo.a one.o two.o 

Then linking your program becomes simpler:

gcc -L. prog.c -loneandtwo 

It's really a matter of packaging. Do you have a set of object files that naturally form a set of related functionality that can be reused in multiple programs? If so, then they can sensibly be archived into a static library, otherwise there probably isn't any advantage.

There is one important difference in the final link step. Any object files that you linked will be included in the final program. Object files that are in libraries are only included if they help resolve any undefined symbols in other object files. If they don't, they won't be linked into the final executable.

like image 83
CB Bailey Avatar answered Sep 19 '22 00:09

CB Bailey