I know that using the static keyword in C on a function restricts the function to the compilation unit in which it is defined. I am now looking into symbol visibility, and I’m a little confused about the difference between static functions and function marked with __attribute__((visibility("hidden"))), or using the -fvisibility=hidden command-line option.
I have a feeling that the way these change things under-the-hood is not at all the same, but I don’t know what the difference is nor what it implies when working with them in actual code. What changes between the two, and when would you want to use one over the other?
A function with
__attribute__((visibility("hidden")))is not visible outside the shared library containing it, but if that library was made by linkingfoo.pic.oandbar.pic.osuch a functionfhidcan be defined infoo.cand called frombar.c. Of course outside code (e.g. from the main program or some other shared library) cannot call thatfhidSo hidden visibility applies to an entire shared library, not to individual compilation units composing it.
In contrast, it would have been possible for
foo.cto define astatic void fsta(void)function, and forbar.cto define a differentstatic void fsta(void)function (even if that is poor taste and should be avoided for readability reasons).Also, in principle, a
staticfunction could be more easily inlined, or the compiler could (sometimes) use different calling conventions for it.