Search code examples
clinkerstatic-libraries

How is object code copied into executable when linking against static library?


I am reading the O'Reilly book 21st Century C, in which the author states that when linking against a static library:

The compiler [is effectively] copying the relevant contents of the library into the final executable.

I have tried to test this by creating my own static library consisting of this module:

static char szStr[64];

char* single_func() {
    strcpy(szStr, "Hello string!\r\n");
    return szStr;
}

void func0() {
    strcpy(szStr, "Hello");
}

char* func1() {
    strcat(szStr, " string!\r\n");
    return szStr;
}

For testing, I created two C files where one is calling single_func() and the other calls func0() and func1().

The resulting executables are 751290B in both cases. If I call strcpy and strcat directly from the modules both executables end up being 7215B.

Does this not conflict with the above statement, or am I missing some detail about linking?

A related question is that the static library is 1600B, so where does this increase in size come from?


Additional:

Both main files consist of nothing more than calling the functions and printing the results, like this:

main0:

#include <stdio.h>
#include "sharedlib.h"
int main() {
    char* szStr = single_func();
    printf("%s", szStr);
    return 0;
}

main1:

#include <stdio.h>
#include "sharedlib.h"
int main() {
    char* szStr;
    func0();
    szStr = func1();
    printf("%s", szStr);
    return 0;
}

Files were compiled like this:

gcc -static main0.c -L. -lsharedlib -o main0

Platform is linux and the compiler is gcc v4.6.3.


Solution

  • With static libraries, the unit of copying is the object file in the library. Since both your programs call a function from the object file, both programs end up with all of the object file in the executable, hence the same size result (give or take the size of the calling main() program).

    The extra information in the executable could come from several places. Some of it will be control and debug information. Some of it might be from the C library if you linked that statically too. We'd probably need to see the main program and the link lines, and know the platform to come up with other reasons for the inflation.