You should use extern
keyword for such cases and not define global variables in headers. Otherwise the linker will throw errors when operating on your header files.
lib.c
#include <avr/io.h>
#include "lib.h"
volatile int var;
void light_led(void)
{
//code here
}
lib.h
extern volatile int var;
void light_led(void);
This way you'll be declaring the global variable in headers and actually defining it in the appropriate source file lib.c
.
Note: Notice the difference between declaring and defining a variable. extern
keyword allows the variable to be declared in advance without being defined. Had you not defined the variable in lib.c
, there would be an error when you tried to use this variable. Since, it is only declared but, not actually defined.
Edit: The whole purpose of static
is to declare that a variable is private to the source file that is declared in. Since, extern
does the opposite by linking a variable defined in another source file, it defeats the purpose of static
. extern
says the variable has external linkage static
says the variable has internal linkage. An identifier can't have both internal and external linkage.
According to MSND:
When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).
For more information check below: