I have a function transpose
declared in a header file global.h
as shown below:
template <size_t M, size_t N>
extern void transpose(array <array <float, N>, M>&, array <array <float, M>, N>&);
The function is defined in another file global.cpp
as shown below:
template <size_t M, size_t N>
void transpose(array <array <float, N>, M>& a, array <array <float, M>, N>& b)
{
// This can be made faster
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
{
b[j][i] = a[i][j];
}
}
}
However, the following function call:
transpose<dim, dim>(jacobian, jacobian_transposed);
throws the error:
undefined reference to `void transpose<23u, 23u>(std::array<std::array<float, 23u>, 23u>&, std::array<std::array<float, 23u>, 23u>&)'
The variable dim
is defined in the global.h
as shown below:
static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num) + 3;
I found this answer. Are there any ways to keep the function definition in the global.cpp
?
Edit: I read the question of which this question was marked as duplicate. That along with the answer from @Xirema helped me realize that I have three options: 1) Implement function in the header.
2) Implement function in a file with '.ipp' extension and include it inside the header.
3) Third option is explicit instantiations like:
template <size_t M, size_t N>
void transpose(array <array <float, N>, M>& a, array <array <float, M>, N>& b)
{
// This can be made faster
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
{
b[j][i] = a[i][j];
}
}
}
template void transpose(array <array <float, dim>, dim>& a, array <array <float, dim>, dim>& b);
template void transpose(array <array <float, dim>, 2>& a, array <array <float, 2>, dim>& b);
Which of the above is the best method (I am trying to follow the best coding practice)?