简体   繁体   中英

Statically compile a C++ app with GCC into a binary

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM