-fvisibility=hidden的用法

来源:互联网 发布:下载播放软件 编辑:程序博客网 时间:2024/05/17 17:44

man gcc:

    -fvisibility=[default|internal|hidden|protected]           Set the default ELF image symbol visibility to the specified option---all symbols are marked with this unless overridden within the code.  Using this           feature can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export           and prevent symbol clashes.  It is strongly recommended that you use this in any shared objects you distribute.           Despite the nomenclature, default always means public; i.e., available to be linked against from outside the shared object.  protected and internal are           pretty useless in real-world usage so the only other commonly used option is hidden.  The default if -fvisibility isn't specified is default, i.e., make           every symbol public.           A good explanation of the benefits offered by ensuring ELF symbols have the correct visibility is given by "How To Write Shared Libraries" by Ulrich           Drepper (which can be found at <http://www.akkadia.org/drepper/>)---however a superior solution made possible by this option to marking things hidden           when the default is public is to make the default hidden and mark things public.  

example code:

foo.c:

void foo(void){}
gcc -shared -fpic -g -fvisibility=hidden  foo.c -o libfoo.so

test.c

void foo();int main(void){foo();return 0;}

gcc test.c  -L. -lfoo/tmp/cciIvtvi.o: In function `main':test.c:(.text+0x12): undefined reference to `foo'collect2: error: ld returned 1 exit status

修改 foo.c如下:

void __attribute__((visibility("default"))) foo(void){}

然后重新编动态库, link通过。