c++ - Function template instantiations not exported to other compilation units, if inlined? -
i'm observing peculiar phenomenon in g++ not export template function instantiations if they're used inlined.. not true regular non-templated functions, of course. example:
// main.cpp #include <iostream> #include "inc.h" int main() { std::cout << func<3>() << std::endl; std::cout << func2() << std::endl; homecoming 0; } // inc.h template<int num> int func(); int func2(); // a.cpp template<int num> int func() { homecoming num; } int func2() { homecoming 5; } int result; int result2; void instantiate() { // store results in globally visible variables // compiler won't optimize them out result = func<3>(); result2 = func2(); }
if compile above -o0
, linking successful - objdump
confirms binary code both func2
, func<3>
generated in a.o
, instantiate
making 2 function calls, ie functions not beingness inlined.
however, -o3
changes things - instantiate
contains no function calls , func<3>
not generated in assembly, causing linker error. func2
still there, of course.
i bitten in real code, expecting functions exported , getting linker errors. behavior expected? compiler convinced generate functions if they're used inline in compilation unit they're implemented in? in case have many template specializations.. explicit instantiation impractical.
c++ templates
No comments:
Post a Comment