C++ programs on the Arduino platform do not have a main()
function like on other platforms; instead, it must have two functions named setup()
and loop()
. But according to C++ standard - all C++ programs must have a main()
function.
So, does such C++ code conform to the standard? Do C++ compilers/linkers/loaders on Arduino conform to the standard?
The C++ standard provides for two execution environments: freestanding and hosted. Most folks here run in a hosted environment, where your program starts inmain()
. Embedded systems run in a freestanding environment, where program startup is through an implementation-defined mechanism. Compilers for a freestanding environment are allowed to leave out some parts of the standard library. For more details, see here.
So, setup()
and loop()
are okay in a freestanding environment. No main()
required. I don’t know if the library for Arduino meets the requirements in the standard.
In a hosted environment, there’s typically an operating system (the host) that lets you launch programs. C++ programs for such an environment must have main()
. In a freestanding environment, the program typically starts when the device is turned on. That’s much closer to the metal, and the system is allowed to have its own requirements, in order simplify the boilerplate code that fires off the application.
Just to have said it out loud here: there is a main.cpp, that looks roughly like this:
#include <Arduino.h>
int main(void) {
init();
setup();
for (;;) {
loop();
}
return 0;
}
The Arduino IDE supplies it. It also generates function prototypes, if they aren't there already, and does some other things.
So, the absence of a main()
in the visible code in the Arduino IDE doesn't mean it isn't there, or that it violates the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With