Undefined reference to method, even though method is defined

I created a template class EWMA in my project, but when using the class in my main.cpp, I get an undefined reference to EWMA<int, 2>::EWMA(float) Error. The .h and .cpp files of this class are inside lib/EWMA/. The .h file looks as following:

#ifndef _EWMA_H
#define _EWMA_H
#include <Filter.h>
template<typename T, int dimensions = 1>
class EWMA : public Filter<T, dimensions> {
    EWMA(float alpha[dimensions]);
    EWMA(float alpha = 0.2);
    std::array<T, dimensions> addValue(T value[dimensions]);
    float alpha[dimensions];
    T value[dimensions];
    bool hasValue = false;

The .cpp file looks like this:

#include <EWMA.h>

template<typename T, int dimensions>
EWMA<T, dimensions>::EWMA(float alpha[dimensions]) {
    this->alpha = alpha;

template<typename T, int dimensions>
EWMA<T, dimensions>::EWMA(float alpha) {
    for (int i = 0; i < dimensions; i++) {
        this->alpha[i] = alpha;

template<typename T, int dimensions>
std::array<T, dimensions> EWMA<T, dimensions>::addValue(T value[]) {
    this->value = this->hasValue ? (1 - this->alpha) * this->value + this->alpha * value : value;
    return this->value;

A very strong simplification of the main.cpp file is as following:
#include <EWMA.h>
EWMA<int, 3>* filter = new EWMA<int, 3>();

Here I get the undefined reference to EWMA<int, 3>::EWMA(float)ā€™` Error, indicating that the method might be declared, but not defined. When I move the content of EWMA.cpp to the .h file, everything compiles fine. Iā€™m not even sure if that is a problem with PlatformIO or if I am missing something about C++ or something completely different.

Any help is much appreciated.

BTW, my other classes in the lib/ folder work just fine.

You cannot implement templates in cpp files that way. See Standard C++. Not a PlatformIO error, purely C++ error.

1 Like