Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the practical difference between a static function and a function with the "hidden" visibility attribute?

Tags:

c

visibility

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?

like image 426
Alexis King Avatar asked Feb 17 '13 09:02

Alexis King


People also ask

How are static functions different from global functions?

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.

What does it mean for a function to be static?

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.

What does Fvisibility hidden do?

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.


1 Answers

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.

like image 161
Basile Starynkevitch Avatar answered Oct 11 '22 13:10

Basile Starynkevitch