Search code examples
c++arduinoavr-gcc

How does this compile in Arduino IDE?


I have noticed the following code, which is obviously invalid C++, compiles in Arduino IDE (using AVR-GCC):

// The program compiles even when the following
// line is commented.
// void someRandomFunction();


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

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

}

void someRandomFunction() {
}

What is going on here? C++ requires functions to be declared before they are used. When the compiler comes to the line someRandomFunction() in the setup() function, how does it know it will be declared?


Solution

  • This is what we call Forward declaration and in C++ it only requires you to declare the prototype of the function before attempting to use it, instead of defining the whole function.:

    Taking as example the following two pieces of code:

    CODE A:

    #include <Arduino.h>
    void setup(){}
    void AA(){
      // any code here
    }
    void loop(){
      AA();
    }
    

    CODE B:

    #include <Arduino.h>
    void setup(){}
    void loop(){
      BB();
    }
    void BB(){
      // any code here
    }
    

    Strictly speaking C requires that functions be forward declared for the compiler to compile and link them. So in CODE A we do not have declared the function but it defined, which makes it legal for proper C code. But the CODE B has the function definition after the loop, which would be illegal for plain C. A solution would be the following one:

    #include <Arduino.h>
    
    void BB();
    
    void setup(){}
    void loop(){
      BB();
    }
    void BB(){
      // any code here
    }
    

    This, however, to fit the Arduino script format of having a void setup() following from a void loop(), required Arduino to include a script on its IDE that automatically looks for functions and generate prototypes up top for you so you do not need to worry about it. So despite being written in C++, you will NOT see Arduino sketches using Forward declaration often in their sketches, as it works out fine and it is often easier to read having first setup() and loop().