Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the visibility attribute be specified in declarations or in definitions?

In his paper about shared libraries, Ulrich Drepper recommends that symbol visibility is globally set to hidden when building the library, and then, in the source code, set to default for each symbol that is meant to be public to export it. However, and after searching it, I still don't understand where should the visibility attribute be specified: in declarations, or in definitions? Since any symbol that is not meant to be part of the interface won't be declared in the public headers, I think the later option is better, but this page from Microsoft makes me doubt: there, the corresponding attribute seems to be set in headers.

For instance, in libwayland, an open-source implementation of the Wayland protocol, it is done as follows:

wayland-client.h:

void wl_event_queue_destroy(struct wl_event_queue *);

wayland-client.c:

WL_EXPORT void
wl_event_queue_destroy(struct wl_event_queue *)
{
    /* ... */
}

I am concerned about compatibility with other compilers and platforms: GCC, Clang, MSVC,... Also note that this question applies to C++ as well.

like image 420
Kalrish Avatar asked Oct 10 '14 13:10

Kalrish


People also ask

What is __ attribute __ (( visibility default?

Summary. To summarize, __attribute__((visibility("default"))) is often used in a shared library, and expected to be compiled with -fvisibility=hidden (though it doesn't have to). Symbols with "default" visibility will always be public outside of the shared library itself.

What is attribute visibility?

With the visibility type attributes, you can control whether and how a structure/union/class or an enumeration that is defined in one module can be referenced or used in other modules. Visibility attributes affect only types with external linkage.

What does Fvisibility hidden do?

-fvisibility=hidden makes all your symbols hidden by default. What you then have to do, is choose which functions you want to be visible to users linking against your library and make them visible by marking them with a visible attribute.


1 Answers

It does not really matter for GNU but on Windows header declarations need to be annotated with dllimports anyway so it's customary to put visibility annotations there as well.

Note that visiblity annotations only need to be enabled when compiling the library itself, not when compiling code which merely calls library functions so most projects do something like

#ifndef WL_EXPORT
# define WL_EXPORT
#endif

in headers.

like image 131
yugr Avatar answered Oct 26 '22 05:10

yugr