#ifndef FOO_H
#define FOO_H
struct Foo{
int randInt = random(0, 101);
};
#endif
I have a header file with a struct
like above but when I compile I get this error:
'random' was not declared in this scope
How can I use random() in a header file?
2 Answers 2
Add #include <Arduino.h>
like this
#ifndef FOO_H
#define FOO_H
#include <Arduino.h>
struct Foo{
int randInt = random(0, 101);
};
#endif
The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:
In foo.h:
#ifndef FOO_H
#define FOO_H
struct Foo{
int randInt;
};
extern struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr);
#endif
In foo.c:
#include "foo.h"
struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr) {
if (!foo_ptr)
return NULL;
foo_ptr->randInt = random(0, 101);
return foo_ptr;
}
random() is a function and therefore its return value cannot be used as static initializer. Unless -std=c++11 or -std=gnu++11 are enabled.
-
It's valid C++ code I don't see why it would be different for an Arduino. The code works fine after I
#include <Arduino.h>
.Chris– Chris2015年10月19日 23:16:40 +00:00Commented Oct 19, 2015 at 23:16 -
What is the outcome? Did you try to compile exactly the code you put in your question?Igor Stoppa– Igor Stoppa2015年10月19日 23:23:04 +00:00Commented Oct 19, 2015 at 23:23
-
I answered my question and it works as is. The only problem was that
random()
was defined in my header file so I had to include the Arduino library. Someone commented for me to do but it's gone now, I guess they deleted it.Chris– Chris2015年10月19日 23:27:13 +00:00Commented Oct 19, 2015 at 23:27 -
With gcc, it works only with -std=c++11 or -std=gnu++11. Probably the Arduino ide turns them on by default.Igor Stoppa– Igor Stoppa2015年10月19日 23:31:00 +00:00Commented Oct 19, 2015 at 23:31
-
1Arduino does in fact have -std=gnu++11 by defaultBrettFolkins– BrettFolkins2015年10月20日 04:54:24 +00:00Commented Oct 20, 2015 at 4:54