Does optimizing for size with
gcc -Os only reduce the binary size of a program, or does it reduce its runtime memory usage as well? I know what exactly the results are depend on the specific code, but in general is the result a lower memory usage?
Obviously, since the program needs to be loaded into memory,
-Os will result in lower memory usage. But that is the only effect on memory usage it will have.
One aspect is that -Os will try to give you a smaller application, and since it is smaller sometimes it will execute faster since there is less code to execute.
Actually, according to some sources like gentoo-wiki, the
-Os flag can have more benefits than just reduced binary footprint. But extensive usage of it can cause problems. The actual benefits can be seen for large programs, but as the flag can trigger some bugs, one must be careful not to use it with unstable code. So, unfortunately, this means that really large pieces of software are more likely to expose bugs (by pure probability: more code => higher risk of bugs exposure). Many large applications filter this flag out at build-time to prevent such bugs from being exposed.
Also keep in mind that
-Os only can make an application faster - this is not a rule. What is certain about it is that the compiler will try to make the program smaller.
As Kim says, the resulting binary is smaller, so the stack memory usage will be smaller too.
It might also be faster than some other optimisation flags, because more of the program will fit into the CPU caches. That's one reason it has become more popular of late.