Search code examples
cgccstatic-linking

C - Compile with dependencies included


I have some code which I want to run on a machine which I do not have root access to. That machine does not have some of the libraries needed to run this code.

Is there any way to include all dependencies when I compile? I realize the resultant file may be quite large.


Solution

  • What you're looking for is static compiling. Performing static compilation includes all of the libraries into the executable itself, so you don't have to worry as much about dependency chains on a specific system, distribution, etc.

    You can do this with:

    gcc -Wl,-Bstatic -llib1 -llib2 file.c
    

    The -Wl passes the flags following to the linker, -Bstatic tells it to link static if possible, and then lib1, lib2, are the libs you intend to link.

    Alternatively, try:

    gcc -static file.c
    

    The compilation will still need to match the architecture of the non-privileged system. And you need to have the static libraries installed on the compiling system (lib.a)

    If compiled properly, it should show "not a dynamic executable" when you run:

    ldd a.out