I have a class with a template method that is declared in a header and defined in a cpp file, so
// A.h - declaration
struct A
{
template<typename T = int> void fun();
};
and then
// A.cpp - definition
#include <iostream>
#include "A.h"
template<typename T> void A::fun()
{
std::cout << "Hello world template" << std::endl;
}
// Explicit instantiation
template void A::fun<int>();
Now, somewhere else, in a test, I have
#include "A.h"
int main ()
{
A a;
a.fun();
}
and since I explicitly instantiated the function for int
template parameter, all is well. Or should be!
My code links fine with GCC 7.3.0 but fails to link with clang 6, which reports an undefined reference to function fun
.
What's going on here? Is there anything else that I should take care of? Perhaps something that GCC takes for granted while clang doesn't?
Thanks!
Edit
@WhozCraig, @Neil Butterworth here are the linking commands for the two toolchains.
GCC:
/usr/bin/g++ -g CMakeFiles/test_generator.dir/generator/generator.cpp.o CMakeFiles/test_generator.dir/test_utils.cpp.o -o test_generator -Wl,-rpath,/home/mleoni/PhD/ABI/libcellml/build/src:/home/mleoni/PhD/ABI/libcellml/build/tests/gtest ../src/libcellmld.so.0.1.0 gtest/libgtest_main.so /usr/lib/x86_64-linux-gnu/libxml2.so gtest/libgtest.so -lpthread
clang:
/usr/bin/clang++ -g CMakeFiles/test_generator.dir/generator/generator.cpp.o CMakeFiles/test_generator.dir/test_utils.cpp.o -o test_generator -Wl,-rpath,/home/mleoni/PhD/ABI/libcellml/build/src:/home/mleoni/PhD/ABI/libcellml/build/tests/gtest ../src/libcellmld.so.0.1.0 gtest/libgtest_main.so /usr/lib/x86_64-linux-gnu/libxml2.so gtest/libgtest.so -lpthread
@IdeaHat: that didn't resolve the issue unfortunately, I am still getting the same error
Edit 2
Since the code I am actually trying to compile is [obviously] not that one, I tried to compile this MWE and both GCC and clang link it fine with just cc A.cpp main.cpp
.
I am now trying to understand what's the difference between this minimal case and the code that I actually have.