n233g16
n233g16

Reputation: 55

How does a C static library work?

What code goes into the final executable when using a library?


As an example, we have two files:

/*main.c*/
int main (int argc, char* argv[]){
    fc(1); /*This function is defined in fc.c*/
}

Another file:

/*fc.c*/
int fc(int x){
    return fe(x);
}
int fe(int y){
    return y + 1;
}

We compile fc.c:

gcc -c fc.c

We then get fc.o.

Now lets build a library named test:

ar rcs libtest.a fc.o

We now have libtest.a.

Now we compile main.c

gcc -c main.c

And we obtain main.o

Let's link our main.o to our libtest.a

gcc -L. main.o -ltest

We get the desired a.out

Checking it's symbols:

nm a.out

In between all the symbols, we find:

080483cc T fc
080483df T fe

Seems good. BUT!

If our main.c changes for this?

/*main.c*/
int main (int argc, char* argv[]){
    fe(1); /*This function is defined in fc.c*/
}

After compiling main.c and linking the new main.o to our library, I will still find a symbol for fc. But I don't need that code.

Questions

-Shouldn't the library "give me" only the code I need in main.c?
-Do the functions need to be in separate modules before being added to the library?
-What if I had 300 functions? Would I need to make 300 modules?

Upvotes: 1

Views: 174

Answers (2)

kfx
kfx

Reputation: 8537

In short, there are compiler flags to prune unused functions from the final executable code, however they are not enabled by default.

GCC can do this "garbage collection" of unused functions if these flags are added:

  1. -ffunction-sections as a compile-time flag. It instructs the compiler to create a separate section (see object file format) for each function. There's also -fdata-sections flag with similar meaning that works for variables.

  2. -Wl,--gc-sections as a link-time flag. The -Wl part instructs GCC to pass the following options to the linker. --gc-sections means "garbage select sections from which all code is unsed". Since due to the compile-time options each function has got a separate section, it effectively performs function-level pruning.

Upvotes: 1

FredK
FredK

Reputation: 4084

Yes, place each function in a separate module. That way the linker will link in only the items needed.

Upvotes: 2

Related Questions