I can easily achieve this in gcc
using the used
and noinline
function attributes (see code below), but this doesn't work in clang
even though it's supposed to support both of these function attributes.
A simplified example:
template<typename T>
struct Factory {
static __attribute__((used, noinline))
T createFoo() { return T(); }
};
int main() {
Factory<int> f; // instantiate and use Factory<int>
}
Compile the code in gcc
and use nm
to confirm that gcc correctly emitted the function:
nm --demangle test | grep createFoo
0000000000403185 W Factory<int>::createFoo()
The code compiles fine in clang
, but it does not emit code for the static createFoo()
function like it's supposed to.
How can I force clang to emit this static function which is never referenced?
As the OP stated in a comment, the semantics of __attribute__((used))
is to treat the function as if it were actually referenced in the code, forcing it to emit code for the function, which clang is not doing in this case.
Furthermore, all class-member-functions have extern linkage as defined by C++. So when the class is instantiated, and the compiler (supporting gcc-style function attibutes) sees __attribute__((used))
for the member function, it should know immediately that an externally visible definition of that function should be emitted. gcc is doing this, bug clang is not.
A temporary workaround (for clang) is to explicitly reference the function somewhere in your code.
You should also file a clang bug report with llvm to get this issue fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With