3
votes

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

1
What's Timer() is supposed to denote? A constructor? In a structure? This is not C.Eugene Sh.
Yes. A constructor. If I delete it, the issue staysuser2136963
Is the first code sample even relevant to your question? And why did you tag this C?Praetorian
The first code sample is to illustrate the difference. I may misunderstand c++ and c.user2136963
Well, they're different languages. Maybe the problem is you're trying to compile your code with a C compiler (although the first example shouldn't have compiled either in that case). Anyway, your second example compiles just fine using a C++ compiler.Praetorian

1 Answers

6
votes

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.