Force definition of symbol for a C++ template instance in a library -
i'd provide library provides template code. keep possible ownership of code (generated code) when can guess usage of different usual types of template. here example of trying do:
lib1.h
#include <iostream> template<int n> void print_me() { std::cout << "i function number " << n << std::endl; }
lib1.cpp
#include "lib1.h" /* force symbols defined here. */ template void print_me<0>(); template void print_me<1>();
i compile library using:
g++ -shared -fpic lib1.cpp -o lib1.so
and when use library:
main.cpp
#include <lib1.h> int main() { print_me<0>(); print_me<1>(); print_me<2>(); }
compiled with:
g++ main.cpp -l1
here expect symbol print_me<0>() , print_me<1>() defined , used lib1.so , print_me<2>() defined , used executable (checked nm --defined-only). seems not case! symbols 0 , 1 defined in lib1.so weak symbols. , redefined in executable (0, 1 , 2) again, weak. implies code 0 , 1 executable taken main.cpp not want (i checked specification in main.cpp).
is there way (in lib1.h instance) @ compile time of main.cpp symbols defined somewhere , not need add these symbols?
c++11 solution: use extern templates. add these strings main.cpp
file:
extern template void print_me<0>(); extern template void print_me<1>();
thus tell compiler not instantiate print_me
function template in main.cpp
(for template arguments 0 , 1). linker should search definition of void print_me<0>();
, void print_me<1>();
in other translation units.
Comments
Post a Comment