How To Write Shared Libraries(25)

2.2.2 Define Global Visibility

The next best thing to using static is to explicitly define the visibility of objects in the DSO. The generic ELF ABI defines visibility of symbols. The specification defines four classes of which here only two are of interest. STV DEFAULT denotes the normal visibility. The symbol is exported and can be interposed. The other interesting class is denoted by STV HIDDEN. Symbols marked like this are not exported from the DSO and therefore cannot be used from other objects. There are a number of different methods to define visibility.
仅次于static的可见性设置是设置DSO的可见性属性。这里只关注四个设置中的两个。
STV DEFAULT标示一般可见性。语法导出可以插入。另一个需要注意的设置是STV HIDDEN。这样标示的DSO不能导出同时内容不能在其他对象中使用。有几种不同的方法设置可见性。

Starting with version 4.0, gcc knows about a the com- mand line option -fvisibility. It takes a parameter and the valid forms are these:
gcc 4.0版本开始支持-fvisibility属性设置。参数如下:

-fvisibility=default 
-fvisibility=hidden 
-fvisibility=internal 
-fvisibility=protected

Only the first two should ever be used. The default is unsurprisingly default since this is the behavior of the compiler before the introduction of this option. When -fvisibility=hidden is specified gcc changes the de- fault visibility of all defined symbols which have no ex- plicit assignment of visibility: all symbols are defined with STV HIDDEN unless specified otherwise. This option has to be used with caution since unless the DSO is prepared by having all APIs marked as having default visibility, the generated DSO will not have a single exported symbol. This is usually not what is wanted.
只有前两个需要注意。默认即是不设置属性时的内容。当gcc设置-fvisibility=hidden除了明确设置的所有的语法都改为STV HIDDEN。这个属性谨慎使用,因为除非预先标记所有需要的API为默认属性,一般的DSO将不会有单独导出标识。这通常是不希望的情况。

In general it is the preference of the author which decides whether -fvisibility=hidden should be used. If it is not used, symbols which are not to be exported need to be marked in one way or another. The next section will go into details. In case the option is used all exported functions need to be declared as having visibility default which usually means the header files are significantly uglified. On the other hand it means that no symbol can accidentally be exported because an appropriate declaration etc is missing. In some situations this can prevent bad surprises.
一般情况下开发者决定是否使用-fvisibility=hidden。如果没有设置,不需要导出的语法标示需要设置一下。下一节分析。如果设置了该项,所有需要导出的内容都需要设置默认可见性,这样的头文件非常糟糕。而且不小心声明错误就会导致没有可导出内容。
在某些情况下,这可以防止糟糕的意外。(有道翻译)。

你可能感兴趣的:(How To Write Shared Libraries(25))