0

I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...

So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)

When I place the functions above the function calls it compiles.

Is this normal behavior or do I have to add some settings to get this working as provided?

Fails in VSCode (works in Arduino IDE):

#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

Works in VSCode (Works in Arduino IDE):

#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}
3
  • did you try them in Arduino IDE?
    – Juraj
    May 11, 2019 at 6:59
  • @juraj, I edited my examples, so you can copy/paste them into the editors. Both examples are working in Arduino, only the below one is working in VSCode
    – Jan
    May 11, 2019 at 8:19
  • 1
    Arduino builder adds function prototypes when converting .ino to .cpp
    – Juraj
    May 11, 2019 at 8:39

2 Answers 2

5

You need to declare your function before you use it. So either the whole function body needs to be before the usage, or you must add a function prototype declaration.

void myfunction();

myfunction();

void myfunction(){
  return 0;
}
5
  • So if I understand you right, this could be done in a header file? I never saw them in the examples I used. But that would make sense...
    – Jan
    May 11, 2019 at 8:08
  • I think Arduino IDE is doing some "magic" behind the scenes to be able to compile without declaring the functions above the function call. I also updated my examples, to be able to copy and paste them into the corresponding IDEs.
    – Jan
    May 11, 2019 at 8:21
  • 1
    void myfunction() should not return an int
    – SBF
    May 11, 2019 at 9:05
  • 2
    @Jan: Indeed. The Arduino IDE edits your .ino file, adds those function prototypes at the beginning of the file, saves the result as a .cpp file, and calls a C++ compiler (g++) to compile that .cpp. May 11, 2019 at 9:29
  • 1
    @Jan, why did you accept an answer which doesn't answer your question?
    – Juraj
    May 11, 2019 at 13:03
0

Just make the the abstract method declaration before writing your code after the header files.

#include<Arduino.h>
void myfunction();
void setup();
void loop();

After this you write your code in any order

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