Passing pointer to extern(C++) templated function

Jamie email at gmail.com
Tue Oct 13 09:23:48 UTC 2020


I'm having difficulties linking templated functions with multiple 
pointer arguments with extern(C++).

a.cpp
-----
template<typename T> void func1(T *b){}
template void func1<int>(int *b);

template<typename T> void func2(const T *a){}
template void func2<int>(const int *a);

template<typename T> void func3(T *b, const T *a){}
template void func3<int>(int *b, const int *a);

template<typename T> void func4(const T *a, T *b){}
template void func4<int>(const int *a, int *b);

void func5(int *b, const int *a){}
void func6(const int *a, int *b){};
-----

main.d
-----
extern (C++)
{
     void func1(T)(T *b);
     void func2(T)(const T *a);
     void func3(T)(T *b, const T *a);
     void func4(T)(const T *a, T *b);
     void func5(int *b, const int *a);
     void func6(const int *a, int *b);
}

void main()
{
     int i = 4;
     int *pi = &i;

     func1(pi);
     func2(&i);
     func3(pi, &i);
     func4(&i, pi);
     func5(pi, &i);
     func6(&i, pi);
}
-----

Building with:
g++ -c a.cpp
dmd main.d a.o

Throws the error:
/usr/bin/ld: main.o: in function `_Dmain':
main.d:(.text._Dmain[_Dmain]+0x31): undefined reference to `void 
func3<int>(int*, int*)'
/usr/bin/ld: main.d:(.text._Dmain[_Dmain]+0x3e): undefined 
reference to `void func4<int>(int const*, int const)'
collect2: error: ld returned 1 exit status
Error: linker exited with status 1

When I inspect the object files, I see the following:
a.o
-----
void func1<int>(int*)
void func2<int>(int const*)
void func3<int>(int*, int const*)
void func4<int>(int const*, int*)
func5(int*, int const*)
func6(int const*, int*)
-----

main.o
-----
void func1<int>(int*)
void func2<int>(int const*)
void func3<int>(int*, int*)
void func4<int>(int const*, int const)
func5(int*, int const*)
func6(int const*, int*)
-----

It appears that func3 and func4 take on different types depending 
on other variables being present? Is this expected? Why do they 
differ from the non-templated functions func5 and func6 
respectively? How should I achieve this instead?



More information about the Digitalmars-d-learn mailing list