Noob question: How to print serial from other file?

I’m trying to refactor a 1 file program to make it a multifile program to standardize it and make it more readable. I sampled one part of the project so I can share and debug separately.

I’m getting this errror: “printer not decaled in this scope”. I’ve been trying to find the name of the issue but its been difficult.

Global variables are not automatically shared between files when using .cpp as they would be when using .ino. You need to have extern delcarations that declare the existance of variable (in name and type, but not value) to other code files.

In your case, in printer.cpp, the easiest would be to add

#include <Adafruit_Thermal.h>
// defined in main.cpp
extern Adafruit_Thermal printer;

at the top of the printer.cpp file.

The stylistically more correct way would be to create a new header file (e.g., printer.h) with an include guard and the above inner content, that can then be included by printer.cpp, instead of directly putting it in printer.cpp.

This is explained in more detail in multiple other topics, e.g.

1 Like

it compiled but did I do it right?

Technically it it doesn’t need #include <SoftwareSerial.h> in the printer.h because none of the types it declares is needed. That’s only needed in the instantiation in main.cpp. Also, for the include guard, you might want to choose a more unique macro name. It’s also customary to at least start with _. E.g.,

#ifndef _MY_PRINTER_H
#define _MY_PRINTER_H

/* content */ 

#endif /* _MY_PRINTER_H */

Also, extern is not need on function declarations. So you can just write

void printticket(int number);

The only exception is when you want to mix C and C++ code, then functions declared in C must have extern "C" before them when included by cpp code, usually done with a whole block declaration of

#ifdef __cplusplus
extern "C" {
#endif

/* function declarations from a .c file */

#ifdef __cplusplus
}
#endif

But that’s not needed for you because your functions are written in a .cpp file and you only call them from a .cpp file.

Besides that, it looks good.

1 Like