Using templates in .cu file with extern "c" declaration

Hi!

I wrote some code in a .cu file:

extern “C”
{
template < typename T> void SensefullFunction(T type)
{
// To do something sensefull
}
}

I want to launch this function from a .cpp file. Without using templates it works fine, but now I get this error:

Error 8 error: this declaration may not have extern “C” linkage

Is it not possible to use templates at the interface between .cpp and .cu - files?

regards!

Sure, you can use templates in a .cu file and call it from a .cpp file. That is possible, because nvcc supports C++ host code in .cu files (and it is turned on on default). With extern “C” this won’t work, because you force the compiler to use simple C name mangling, but templates make C++ name mangling mandatory. Because you used extern “C” with a template function, I think you do not really know what it does: read this article.

Really!? But then, I have to call a host function in a .cu file from a .cpp file without extern “c” declaration. I thought that’s not possible…

If there is any way, please give me a short example. The sdk example shows only how work with .cpps and extern “c”.

regards!

nvcc supports C++ host code, but a template must be known at compile time. So my answer was not completely correct: you cannot define a template-function within a .cu file and use it from a .cpp file (unless you include the .cu in your .cpp). But you can define a template function within a .cu file and use it there. Or you define it in a header (.cuh) and include that one in both files, .cu and .cpp.