0

I have code that looks something like this (compiling using the Arduino IDE).

main sketch file:

#include "myHeader.h"

//setup stuff here, including setting up Serial & SerialBT

loop(){
  CheckForMessages(&Serial);   //Check USB first
  CheckForMessages(&SerialBT); //Then check Bluetooth
}

myHeader.h:

#include "Arduino.h"
//other includes

template <class T> void CheckForMessages(T *port);

//declarations of other stuff

myHeader.cpp:

#include "myHeader.h"

template <class T> void CheckForMessages(T *port){
  if(port->available() !=0){
    //rest of function...
}

//definitions of other stuff

When I compile, I get the "undefined reference" errors for both calls to CheckForMessages in the main sketch file. This goes away if I move the definition of the template into the .h file.

I have no issues splitting the declaration and definition of functions in this way as far as I can tell, can anyone explain to me why it isn't working for my templates?

JRVeale
  • 394
  • 2
  • 10
  • 1
    Templates need to be defined in headers. – Yunnosch Mar 18 '19 at 11:13
  • Ah, thank you, I just found this: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file which explains why well. Edit: I missed this rule previously because I was in the bad habit for a while of including .cpp files instead of .h files – JRVeale Mar 18 '19 at 11:17
  • And now you got a glimpse of why that is considered unwise... – Yunnosch Mar 18 '19 at 13:00

0 Answers0