1

How do I statically compile an app with GCC on a Ubuntu machine targeting unix? And how would I target 32-bit/64-bit machines and machines with different versions of GLIBC or whatever a unix C++ app is typically dependent on? I want to then distribute this app in binary form and run it on a unix machine without needing to compile from source.

Similarly, can I compile this app on Windows such that it will run on unix?

Community
  • 1
  • 1
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • 4
    You cannot "target Unix" in general. If you build a Linux binary, it will run only on Linux systems. FreeBSD has a Linux compatibility layer, but that's the only exception. The binary will not run on Mac OS X, nor Solaris, nor on other Unix systems. – Nikos C. Oct 29 '12 at 08:27
  • 1
    If you want to proof yourself from different verisons of the clib and standard library on different unix machines u want the flags -static-libgcc and -static-libstdc++. This embeds them in the file so you are not dependent of the .so files on the system where it will run – Rolle Oct 29 '12 at 08:33
  • @Rolle - Can you please add your comment as an answer? Its very useful. – Robin Rodricks Nov 02 '12 at 05:54

2 Answers2

3

To compile it so it will run on Linux just compile it like so:

g++ -o myapp myapp-a.cop myappb.cop -L mylib1

This should work on most versions of Linux, and some versions of FreeBSD too.

This does not statically link against libstdc++, but this is maybe a better way to go. as a rule of thumb you should dynamically link against the OS c lib to allow your app to work even if the syscall abi changes.

You can force a 32 bit compile from a 64 bit machine with '-m32' as one off your flags. It sets the compilation mode to 32 bit.

As for compiling on Windows: yes. you can do it. it is called cross compiling. You first need to compile a toolchain that will target Linux.

Will
  • 4,585
  • 1
  • 26
  • 48
  • Unfortunately, this recipe will NOT work on systems which use different versions of glibc or libstdc++ (like older Linux systems) because you do not use static compilation. – mvp Oct 29 '12 at 10:51
2

This is how you can create statically compiled 32-bit only executable, which should work on any known Linux without complaining for missing libs:

g++ -m32 -static -o myprog myprog.cpp

One downside to this is that minimum size for executable will be at least 600 KB.

Note: if you are getting compilation errors, be sure to have package g++-multilib installed.

mvp
  • 111,019
  • 13
  • 122
  • 148