Skip to content
Advertisement

Is it possible to compile statically with gcc or g++ on Linux based systems?

I am working on a project which I would like to be able to “ship” to other Linux based computers as a complete executable with no dependencies. (In order that I can copy just the 1 file to other systems, and then run that file on those systems.)

In the windows world, I think static linking is done just by passing -static to the compiler, perhaps with some other options for specific libraries*, if you are using Visual Studio.

*eg: Using SFML you also have to define SFML_STATIC for some reason?

Is this possible using gcc / g++, and if so how? I tried searching for this but didn’t manage to find anything. I have heard before that this may be a non-trivial task.

Edits:

BasileStarynkevitch suggested compiling with the flag -static.

I don’t know if this is what I want, but I wrote a test program to try it out:

#include <iostream>

int main()
{
    std::cout << "Link statically please" << std::endl;

    return 0;
}

And then compiled with:

g++ main.cpp -o a.out -static
g++ main.cpp -o b.out

The results are:

-rwxr-xr-x  1  1653098  a.out
-rwxr-xr-x  1     9167  b.out

So it looks like it might be working?

TonyD suggested a method of checking:

ldd a.out 
not a dynamic executable

ldd b.out
linux-vdso.so.1 =>  (0x00007fff3d5ac000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fce5e34a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fce5df85000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fce5dc7e000)
/lib64/ld-linux-x86-64.so.2 (0x00007fce5e677000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fce5da67000)

Advertisement

Answer

Compiling with -static appears to work for basic c++ programs, probably all of the standard library?

However when using with other libraries, this may no longer work.

Advertisement