歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux 下 GCC 編譯共享庫控制導出函數的方法

Linux 下 GCC 編譯共享庫控制導出函數的方法

日期:2017/3/1 9:20:29   编辑: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 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved