8

The following sketch to fails to compile in the Arduino environment.

Given that typedefs can be used within Arduino software, is Automatic Prototype Generation the underlying mechanism that causes the failure? If so, what is it and why isn't Arduino providing a lightweight wrapper around C++?

#define PRODUCE_WACKY_COMPILETIME_ERROR
typedef int MyMeaningfulType;

#ifndef PRODUCE_WACKY_COMPILETIME_ERROR
void myFunc(MyMeaningfulType myParam);
#endif

void myFunc(MyMeaningfulType myParam)
{
  myFunc(10);
}

void setup() {}
void loop() {}

For the benefit of the search engines, the errors reported are:

error: variable or field 'myFunc' declared void
error: 'MyMeaningfulType' was not declared in this scope
1
  • Great summary of the problem. I had the same issue. When I ran a sketch in the context of the library examples, everything worked. But when I created a new sketch, copied the example sketch and added the library, I got the errors described by the OP. Declaring the functions at the top of the file or in a separate .h file fixed the problem. Commented Aug 25, 2023 at 20:05

2 Answers 2

8

Please refer to http://arduino.cc/en/Hacking/BuildProcess the specific quote is:

This means that if you want to use a custom type as a function argument, you should declare it within a separate header file.

This page does a good job of explaining how the Arduino Language is different from C/C++ in how it works/pre-processes files.

Sign up to request clarification or add additional context in comments.

Comments

0

They are attempting to create prototypes for every function they find. Unfortunately, if you define a typedef in the file before the function, and use that in a function definition, the place they put the function prototype does not see it, and this generates a syntax error.

If you use the 'struct * ' syntax instead in those function definitions, you benefit from C's 'opaque type' facility, in which you can use a struct definition without having it be declared beforehand. So, build the typedef, use it, but use the struct definition in any functions that use the typedef in arguments.

typedef struct mytype_ {
    int f1;
} mytype_t;

void myfunc(struct mytype_ * xxx) {
    xxx->f1 = 1;
}

Comments

Your Answer

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.