I have some code that seems to me like it ought to work but throws an error when compiling.
The header file (min.hpp
):
#include <type_traits>
namespace test {
template <typename T1>
T1 min(T1 a);
template <typename T1, typename ... Args>
typename std::common_type<T1, Args...>::type min(T1 a, Args ... args);
}
The implementation (min.cpp
):
#include <type_traits>
namespace test {
template <typename T1>
T1 min(T1 a)
{
return a;
}
template <typename T1, typename ... Args>
typename std::common_type<T1, Args...>::type min(T1 a, Args ... args)
{
typename std::common_type<Args...>::type b = min(args...);
return a > b ? b : a;
}
}
Calling the function (demo.cpp
):
#include <cstdio>
#include "min.hpp"
int main()
{
int x = test::min(1, 2, 3);
std::printf("%d\n", x);
return 0;
}
Compiling:
g++ min.cpp demo.cpp -std=gnu++17 -o main
Error message:
Undefined symbols for architecture x86_64:
"std::__1::common_type<int, int, int>::type test::min<int, int, int>(int, int, int)", referenced from:
_main in demo-5e729b.o
ld: symbol(s) not found for architecture x86_64
However, the code works fine if I move the main()
function from the separate file to min.cpp
.
Why do I get this error and how can I fix it?