内联模板函数的可见性



编译背后的合理性是什么

namespace ns __attribute__((visibility("default"))) {
template<typename T>
inline int func1(const T& x) {
return x;
}
inline int func2(int x) {
return x;
}
struct test {
template<typename T>
int func3(const T &x) { return x; }
int func4(int x) { return x; }
};
}
int __attribute__((visibility("default"))) client(int x) {
ns::test t;
const int y1 = ns::func1(x);
const int y2 = ns::func2(x);
const int y3 = t.func3(x);
const int y4 = t.func4(x);
return y1 + y2 + y3 + y4;
}

g++ -Wall -fPIC 
-fvisibility=hidden -fvisibility-inlines-hidden 
-shared -o libtest.so test.cpp

产生一个导出ns::test::func1<int>()ns::test::func3<int>()但不是ns::func2()也不是ns::test::func4()的库?这两个模板函数都是inline定义的,-fvisibility-inlines-hidden告诉编译器隐藏它们——或者至少它们的实例化,希望它们也是内联的。

显式func1func3隐藏函数模板,即使用

template<typename T>
int __attribute__((visibility("hidden"))) func(const T &x) { return x; }

导致预期行为。省略命名空间定义中的默认可见性会隐藏这两个实例化。

背景:我们尝试尽量减少库中可见符号的数量。因此,我们使用上述编译器标志和属性。当然,这对于所有静态第三方库也是必要的。但不幸的是,包含的头文件中的那些内联模板函数完全不受我们的控制。例如,每个实例化

namespace std {
template<typename _CharT, typename _Traits, typename _Alloc>
inline bool
operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
const _CharT* __rhs)
{ return __lhs.compare(__rhs) == 0; }
}

#include <string>将很乐意在我的图书馆内生成一个公开可见的符号。最烦人的部分是,它会放在我的库中,没有任何版本信息,所以没有GLIBCXX_3.x.z区分。

奖励问题:使用链接器脚本的总体影响是什么

{
global:
_Z6clienti;
local:
*;
};

据我了解,这只有在我不使用任何异常处理或跨库边界的动态类型转换时才真正可行。但是这些内联函数会发生什么?感觉整个隐藏可见性的事情无论如何都违反了一个定义规则,因此这没什么大不了的。

GCC 不尊重模板函数的-fvisibility-inlines-hidden;这是一个从 gcc-10 开始修复的错误。

在 GCC 10 中,所有四个函数都具有隐藏的可见性(命令行标志优先于封闭命名空间上指定的可见性属性(。

最新更新