justinvdk
justinvdk

Reputation: 172

Arduino: static StringObject in class' method and main function

I've got an existing program for AVR that uses a main function, and not a setup and loop. This seems to be needed as it makes use of timers and doesn't work when I manually replace it with setup and loop.

This works fine but I wanted to include some code from a library and now the compiler complains about multiple definitions of main. This is odd as nothing really is included and I declare my own main (so no sneaky default main function) and I've isolated to the following case:

int main()
{

}

// Foo.h
class Foo
{
  void bar();
};

// Foo.cpp
void Foo::bar()
{
  /* remove static here */
  static String foo;
}

The compiler starts complaining once I declare the String foo in the bar method. But only when it is declared static. Otherwise the code compiles.

I'm not a cpp guy and can't figure out why declaring a static variable inside a method would trigger this.


  1. Is this a bug in the Arduino framework? Or am I missing something obvious?
  2. If this is working as intended, what would be the best alternative?

My understanding (ignoring template classes) is that there is a single copy of foo; so I could declare it globally or as member variable for the class (the latter being technically different but there will only ever be a single instance of this class).

The error I'm getting:

// previous stages succeed
...
Linking everything together...
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/path/to/build/static_in_cpp_method.ino.elf" "/path/to/build/sketch/static_in_cpp_method.ino.cpp.o" "/path/to/build/../arduino_cache_993247/core/core_arduino_avr_pro_cpu_16MHzatmega328_51f02b7210b938436b779d1c032618e1.a" "-L/path/to/build" -lm
main.cpp.o (symbol from plugin): In function `atexit':
(.text+0x0): multiple definition of `main'
/path/to/build/sketch/static_in_cpp_method.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Pro or Pro Mini.

Upvotes: 0

Views: 292

Answers (1)

MihanEntalpo
MihanEntalpo

Reputation: 2072

  1. You shouldn't define your own main() function.

  2. Add void loop() and void setup() functions

  3. The code, that you wanted to place in main() function, should be separated into two parts:

    • initialization code should be placed into setup(),
    • and "main loop" code - into loop() function.

And your code would happily compile with or without static keyword.

Upvotes: 0

Related Questions