I have created a library Lib
that doesn't have a class. I want this library to have a variable that can be accessed from outside. The way I would go about this is to just declare them in the header file.
However, if I do this like so:
int myVariable = 1;
with the .cpp
-file containing only
#include "Lib.h"
I get this error message when compiling an empty sketch that includes this library:
multiple definition of `myVariable'
and for some weird reason
Multiple libraries were found for "Lib.h"
on top of that (although, this is something I have encountered before - when there is some error during the compilation, this error may come alongside it, even though there are no multiple libraries; it goes away when the other compilation errors are resolved aswell).
What is causing that error and how to resolve it?
2 Answers 2
In Lib.h you should declare an
extern int myVariable;
In Lib.cpp you can define it once
#include "Lib.h"
int myVariable=123;
...
-
What is the problem assigning it in the C file instead of the header file (since the C file includes the header file, everything is available at compile time)?Michel Keijzers– Michel Keijzers2019年12月10日 14:02:47 +00:00Commented Dec 10, 2019 at 14:02
-
1
I can't use it for purposes that need the variables value known at compile time.
-- Then you shouldn't be using a variable. If it's wanted at compile time then you need a constant, not a variable. Variables change. If it's wanted at compile time then you really don't want it to change. It should be a constant or a #define.Majenko– Majenko2019年12月10日 14:22:26 +00:00Commented Dec 10, 2019 at 14:22
If you want a "variable" that is used at compile time, for instance to set the size of an array, then a variable is not what you want.
Variables change. That's what "variable" means. If you are using it for something at compile time then it can't be variable, since it must never change.
Ergo, you want either a constant or a #define
macro which is replaced with a literal. Both of these can be done in the header, since they both by default have local TU scope:
const int myVariable = 123;
Or to use a macro:
#define SAMPLE_ARRAY_SIZE 123
const int myVariable = 1;
if it is a constant