1
#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?

asked Oct 19, 2015 at 22:46

2 Answers 2

2

Add #include <Arduino.h> like this

#ifndef FOO_H
#define FOO_H
#include <Arduino.h>
struct Foo{
 int randInt = random(0, 101);
};
#endif
answered Oct 19, 2015 at 23:18
2

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.

answered Oct 19, 2015 at 23:01
6
  • 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>. Commented Oct 19, 2015 at 23:16
  • What is the outcome? Did you try to compile exactly the code you put in your question? Commented 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. Commented 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. Commented Oct 19, 2015 at 23:31
  • 1
    Arduino does in fact have -std=gnu++11 by default Commented Oct 20, 2015 at 4:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.