Ingo
Ingo

Reputation: 736

Understanding C++ visibility support

-- as described at the GCC Wiki - Visibility. I have exercised How to use the attribute((visibility("default")))? and Simple C++ Symbol Visibility Demo but still do not understand some parts of the GCC Wiki - Visibility article.

At its Step-by-step_guide you find

For every non-templated non-static function definition in your library (both headers and source files), decide if it is publicly used or internally used

In the other examples I found that it is sufficient to only decorate the declarations in the header files. Why also decorate the definitions in the source files?

If it is publicly used, mark with FOX_API like this: extern FOX_API PublicFunc()

I haven't seen this extern keyword in the other examples and I have never used it for public functions. Why do I have to use it here?

The given macro starts with

#ifdef FOX_DLL // defined if FOX is compiled as a DLL

If using CMake where or how is FOX_DLL defined?

Upvotes: 2

Views: 2020

Answers (2)

MSalters
MSalters

Reputation: 179799

You might be confused by two opposite approaches to visibility. You name both GCC (which comes from the UNIX corner) and DLL (which comes from the Windows corner).

UNIX by default has full visibility, Windows by default has no visibility. As a result, to modify these two defaults, you have to move in opposite directions.

C++ (and C prior to it) did not have the notion of shared libraries or visibility, which makes sense: there wasn't much to standardize. You end up with non-portable approaches like this.

Upvotes: 1

yugr
yugr

Reputation: 21886

In the other examples I found that it is sufficient to only decorate the declarations in the header files. Why also decorate the definitions in the source files?

If global function is declared in a header and that header is included in source file where function is defined, annotation in header will suffice (compiler will indeed pick up the attribute from the header). Otherwise you'll need to annotate it in source code.

I haven't seen this extern keyword in the other examples and I have never used it for public functions. Why do I have to use it here?

The extern keyword is optional in function declarations but it's often used for clarity.

Upvotes: 1

Related Questions