0

Originally this works (file init.cpp):

#include "main.h"
#include "api/llemu.h"
#include "api/lcd.hpp"
template<typename ... Args>
void lcd_print(std::int16_t line,std::string fmt,Args ...args){
  const char* format = convert(fmt,args...);
  if (line >= 1 && line <= 8) {
    llemu::editLabel(lines[line - 1], format);
  }
}
void initialize() {
    llemu::init();
  lcd_print(1,"hey");
}

But when I try to implement the function template in a hpp file, it doesn't work. New code:

//init.cpp
#include "main.h"
#include "api/llemu.h"
#include "api/lcd.hpp"
void initialize() {
    llemu::init();
  lcd_print(1,"hey");
}

//lcd.hpp
template<typename ... Args>
void lcd_print(std::int16_t line,std::string fmt,Args ...args);

//lcd.cpp
template<typename ... Args>
void lcd_print(std::int16_t line,std::string fmt,Args ...args){
  const char* format = convert(fmt,args...);
  if (line >= 1 && line <= 8) {
    llemu::editLabel(lines[line - 1], format);
  }
}

There is a linker error in the new code:

[undefined reference to `void lcd_print<>(short, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)]

What does it mean and what did I do wrong?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Eden Cheung
  • 303
  • 2
  • 8
  • Template resolution requires the code to be available at compile time. By separating the implementation out to another source file that is not included by whatever uses this template, the template can no longer be resolved. – paddy Jul 16 '19 at 04:56
  • will putting the whole template in the hpp file work? – Eden Cheung Jul 16 '19 at 04:56
  • 2
    Yes, and indeed that is commonly why the `.hpp` extension is used instead of `.h` -- it commonly informs you that the header contains an implementation such as inline code or templates. That is just a convention, and not required or otherwise enforced. I thought I would mention it anyway. – paddy Jul 16 '19 at 04:59
  • 2
    The `.hpp` extension is not used consistently, sometimes it is used to indicate that it is a c++ header, sometimes that it not only includes the declarations but also some but not all definitions and sometimes it is used to indicate that it is completely header only. That varies between libraries, so the `.hpp` can be an indicator, but you always need to check what the naming convention of the library you use is because the standard itself does not define anything bout that @paddy – t.niese Jul 16 '19 at 05:26
  • Thank you for taking the time to agree with me in a more concise manner. – paddy Jul 16 '19 at 05:36

0 Answers0