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?

2

Add #include <Arduino.h> like this

#ifndef FOO_H
#define FOO_H

#include <Arduino.h>

struct Foo{
  int randInt = random(0, 101);
};

#endif
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.

  • 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 Oct 19 '15 at 23:16
  • What is the outcome? Did you try to compile exactly the code you put in your question? – Igor Stoppa Oct 19 '15 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 Oct 19 '15 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 Oct 19 '15 at 23:31
  • 1
    Arduino does in fact have -std=gnu++11 by default – BrettAM Oct 20 '15 at 4:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.