Why there is no main() function ?

Hi there !

I've been programming microcontrolers with C language but I am new to Arduino.
Using the example codes I notice that there is no main function, only setup and loop...

Also, I've tried to create a variable inside the loop function, but the program didn't behave the way I expected. Although I didn't get any error message. I only worked when I put the variable outside the functions, making it a global variable.

Thanks !

main() is provided for you.

Also, I've tried to create a variable inside the loop function, but the program didn't behave the way I expected. Although I didn't get any error message. I only worked when I put the variable outside the functions, making it a global variable.

Yes so? this is C and that's how it works.

Mark

It might be an idea to look at main.cpp in the Arduino core library files:

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif
    
    setup();
    
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
        
    return 0;
}

CarlosEC:
Also, I've tried to create a variable inside the loop function, but the program didn't behave the way I expected. Although I didn't get any error message. I only worked when I put the variable outside the functions, making it a global variable.

Post your code please.

How to use this forum

CarlosEC:
I've been programming microcontrolers with C language but I am new to Arduino.
Using the example codes I notice that there is no main function, only setup and loop...

The "main()" function is in the Arduino core library.
So it is invisible, if you do not look up the source code of the core library.

But if you like, you can write your own "main()" function in an Arduino sketch and this will compile.

CarlosEC:
Also, I've tried to create a variable inside the loop function, but the program didn't behave the way I expected. Although I didn't get any error message.

The Arduino IDE shows no compiler "warnings", but only "errors". So everything you program that normally would show up a "warning" will show nothing at all in the Arduino IDE.

Variables declared outside of functions are "global" and variables declared inside of functions are "local". Nothing else as with plain C.

I suggest you do what Nick Gammon suggested :grin: You can't get a better teacher :grin:

main() is omitted (actually, hidden away in the core) and replaced with setup()/loop() to emphasize some of the differences between programming a microcontroller and programming a more traditional computer. (In particular, loop() runs over and over again, so you don't have to explain what happens when main() exits.)

You can still use it, for example:

int main()
{
    init(); // this is needed

    Serial.begin( 9600 );

    for ( ;; )
        Serial.println( millis() );
}

This is equivalent to:

void setup()
{
    Serial.begin( 9600 );
}

void loop()
{
    Serial.println( millis() );
}