Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are functions generated on use of template have "weak" as symbol type?

Created a template function C++ template <class T> void myswap(T&d,T&s). Main uses it for int, double, complex types. Compiled the source using g++. On dumping the symbol table via nm, the functions generated for the respective types have symbol type "W".

Why are they generated as weak symbols?


#include <iostream>
#include <complex>

template <class T>
void myswap(T& d, T& s)
{
    T temp = d;
    d=s;
    s=temp;
}

int main(void)
{
    int m=5,n=6;
    std::cout << "m=" << m << " n=" << n <<std::endl;
    myswap(m,n);
    std::cout << "m=" << m << " n=" << n <<std::endl;

    double p=4.3,q=5.6;
    std::cout << "p=" << p << " q=" << q <<std::endl;
    myswap(p,q);
    std::cout << "p=" << p << " q=" << q <<std::endl;

    std::complex<double> r(2.3,5.7), s(1.2,3.4);
    std::cout << "p=" << r << " q=" << s <<std::endl;
    myswap(r,s);
    std::cout << "p=" << r << " q=" << s <<std::endl;

    return 0;

}
like image 695
TheExcitedEngineer Avatar asked Oct 19 '25 00:10

TheExcitedEngineer


1 Answers

Function template specializations that are generated by implicit instantiation are similar to inline functions in that if multiple translation units generate the same instantiation, the ODR is not violated. If this were not so, then templates would be almost unusable.

Weak linkage is the mechanism used to make this possible in a typical implementation.

like image 61
Brian Bi Avatar answered Oct 20 '25 15:10

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!