The error is because the variable is defined in the Sketch1.ino file but you try to use it in libreria.h , even though X is a global variable, this does not mean that libreria.h the fence to see, you must declare the variable in libreria.h as an external variable the which is defined is in Sketch1.ino , your two files would look like this:
libreria.h
extern int X; //DECLARACIÓN de X como variable externa
void funcion1()
{
X = 1;
}
void funcion2()
{
X = 2;
}
void funcion3()
{
X = 3;
}
Sketch1.ino
#include "libreria.h"
int X = 0; //DEFINICIÓN de la variable X
void setup()
{
Serial.begin(9600);
}
void loop()
{
funcion1();
Serial.println(X,DEC);
funcion2();
Serial.println(X,DEC);
funcion3();
Serial.println(X,DEC);
}
What is an external variable?
Briefly, there is a difference between Declare a variable and Define a variable:
-
Definition - when a variable is defined, the compiler is told that there is a variable of a certain name and data type, and this allocates memory and a value.
-
Statement - when a variable is declared, the compiler is informed that there is a variable with that name and that type of data, but this does not need to be assigned memory or value because that was already done elsewhere, just know that it exists and already.
Now an external variable is a variable defined outside the function block or scope, in C language and all its direct descendants like C ++ and Objective-C, inherit some reserved words called auto , > static , extern and register .
These reserved words control the type of storage of the variable, if it is not assigned manually, they are assigned automatically depending on the area where they are located, a variable that is defined within a function, is automatically assigned as automatic (auto ) and memory is assigned when the function starts and it is deleted when it ends.
The reserved word Extern informs the compiler that this variable is a declaration of a global variable and that its definition is somewhere else. >.