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?
Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.
A static function is a member function of a class that can be called even when an object of the class is not initialized. A static function cannot access any variable of its class except for static variables. The 'this' pointer points to the object that invokes the function.
Parts of LLVM are compiled with -fvisibility=hidden . This option forces the default visibility of all symbols to be hidden , which prevents them from being visible across library boundaries. Hiding symbols offers better control over exported symbols in a shared library.
A function with __attribute__((visibility("hidden")))
is not visible outside the shared library containing it, but if that library was made by linking foo.pic.o
and bar.pic.o
such a function fhid
can be defined in foo.c
and called from bar.c
. Of course outside code (e.g. from the main program or some other shared library) cannot call that fhid
So hidden visibility applies to an entire shared library, not to individual compilation units composing it.
In contrast, it would have been possible for foo.c
to define a static void fsta(void)
function, and for bar.c
to define a different static void fsta(void)
function (even if that is poor taste and should be avoided for readability reasons).
Also, in principle, a static
function could be more easily inlined, or the compiler could (sometimes) use different calling conventions for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With