C++ -fvisibility=hidden -fvisibility-inlines-hidden
Asked Answered
S

2

34

I have a question about the C++ visibility attribute. I have read http://gcc.gnu.org/wiki/Visibility and yet I dont quite understand how it works.

I want use the visibility to be hidden on some of my shared libraries I have. I believe this means that the symbols are hidden ?

How are you meant to link the shared library then ? Is there a special way ? If I link it how it normally gets linked it doesnt work.

Can someone help me please.

Scop answered 25/8, 2010 at 21:28 Comment(0)
J
56

-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.

E.g.

void __attribute__((visibility("default"))) Exported()
{
    // ...
}
Jolin answered 25/8, 2010 at 21:37 Comment(1)
And naturally you will want to create a macro like MYLIB_PUBLIC or something similar to make this cleaner.Disembodied
S
13

It reduces storing unnecessary symbol information that is private to the Shared Objects.

Consider a shared object which has more than 10,000 symbols (functions/global variables), but only 100 of them were public functions accessible to the library users. We can make the only 100 functions as visible to others and remaining 9,900 symbols shall be kept private.

It can be also used to reduce shared object's size, because its relocation table will have only 100 symbols of information. Using this flag along with -ffunction-sections -fdata-sections will reduce the shared object size further by having the definition which is relevant to those 100 symbols.

Surgeonfish answered 21/1, 2013 at 5:4 Comment(2)
It was such a nice answer, but what if I use -fPIC -no-plt together with linker options: -z now -z retro? In this way, lazy loading is disabled completely. So are relocations.Waterrepellent
@AlirezaMohamadi I think -z retro is maybe -z relro? IIUC the downside to your suggestion is that you're forcing eager resolution of all symbols which can lead to slower startup time (e.g. forces resolution of all symbols at dlopen).Kokanee

© 2022 - 2024 — McMap. All rights reserved.