user2136963
user2136963

Reputation: 2606

Arduino struct does not name a type error

In Arduino IDE I can create variables with custom types, but cannot return custom type from function:

This compiles

struct Timer
{
  Timer()
  {
  }
};

Timer t;
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}
int main()
{
  return 0;
}

This creates Timer does not name a type error:

struct Timer
{
  Timer()
  {
  }
};

Timer get_timer()
{
  return Timer();
}

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}
int main()
{
  return 0;
}

Both compile in Orwell Dev-Cpp

I use MEGA-2560

Upvotes: 3

Views: 2410

Answers (1)

Artium
Artium

Reputation: 5331

You can read here about the build process of the Arduino IDE.

Before it can be compiled, your sketch needs to be transformed into a valid C++ file.

Part of this transformation is to create function defitions for all your function declarations.

These definitions are put in the top of the file, before your definition of Time. Therefore at the point of declaration of get_timer, the type Time is not declared yet.

One way to overcome this is to put all your type definitions in a separate .h file and include it into your sketch.

Upvotes: 6

Related Questions