手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux 下 GCC 编译共享库控制导出函数的方法

[日期:2015-12-05] 来源:Linux社区  作者:Linux [字体:大 中 小]

通过一些实际项目的开发,发现这样一个现象,在 Windows 下可以通过指定 __declspec(dllexport) 定义来控制 DLL(动态链接库)中哪些函数可以导出,暴露给其他程序链接使用,哪些函数是 DLL 内部自己使用;而在 Linux 下不存在 dllexport 这样的指示字,默认情况下 GCC 编译 SO(共享库)时把代码中的所有函数都导出了,那么如何实现 Windows 下的那种效果,由我们自己来控制共享库导出函数呢?

其实在 Linux 下也有类似的控制机制。在 GCC 帮助文档中,对 -fvisibility=default|internal|hidden|protected 参数及其取值有这样一段描述:

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. This is the norm with DLL's on Windows and with -fvisibility=hidden and "__attribute__((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. This is a great boon to those working with cross-platform projects.

需要了解的是,在 Linux下,源文件中的所有函数的 visibility 属性都被默认设置为 public,在编译命令中加入 -fvisibility=hidden 参数后,会将所有默认的 public 属性变为hidden。此时,如果对函数设置 __attribute__((visibility("default"))) 参数,则该函数按 public 属性处理,-fvisibility=hidden 参数不会对该函数起作用。所以,针对 GCC 设置了 -fvisibility=hidden 参数之后,只有设置了 __attribute__((visibility("default"))) 属性的函数才是对外可见的,如此则效果等同于 Visual Studio 下的 __declspec(dllexport) 定义。比如:

extern int foo(int a, int b, int c) __attribute__((visibility("default")));

这样声明即可。

Linux升级GCC 4.8.1清晰简明教程(Ubuntu 12.04 64位版为例)  http://www.linuxidc.com/Linux/2014-04/99583.htm

在CentOS 6.4中编译安装GCC 4.8.1 + GDB 7.6.1 + Eclipse 在CentOS 6.4中编译安装GCC 4.8.1 + GDB 7.6.1 + Eclipse

Ubuntu下Vim+GCC+GDB安装及使用 http://www.linuxidc.com/Linux/2013-01/78159.htm

Ubuntu下两个GCC版本切换 http://www.linuxidc.com/Linux/2012-10/72284.htm

CentOS6.5升级手动安装GCC4.8.2  http://www.linuxidc.com/Linux/2015-01/112595.htm

GCC 的详细介绍:请点这里
GCC 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-12/125919.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款