简体   繁体   中英

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.

It does not really matter for GNU but on Windows header declarations need to be annotated with dllimport s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM