arduino / ArduinoCore-arc32

GNU Lesser General Public License v2.1
329 stars 284 forks source link

Runtime problem with example #355

Open jimaobian opened 7 years ago

jimaobian commented 7 years ago

Hi. When we try to use singleton, inherit and customized constructor at the same time this problem will occur. Please see the following example. You can comment the customized constructor to eliminate this problem

OS: Tested on Windows and Mac. Arduino IDE: Version 1.6.13. Arduino 101 Board Manager: Version 1.0.7. Firmware updated.

class test1
{
  public:
    test1(){};  // You can comment this line to eliminate this runtime problem
    virtual void execute();  
};

class test2 :public test1
{
  public:
//    test2(){};  // You can comment this line to eliminate this runtime problem
    void execute(); 
    static test2* instance();
};

test2* test2::instance()
{
  static test2 state;
  return &state;
}

void test2::execute()
{
  Serial.println("hello");
}

test2 *mytest = NULL;

void setup() {
  Serial.begin(115200);
  while(!Serial);
  mytest = test2::instance();  
  Serial.println("test begin");
}

void loop() {
  mytest->execute();
  delay(100);
}
eriknyquist commented 7 years ago

Hi @jimaobian, can we have a bit more information please? like, for example, 1) what is the expected outcome of your sketch above, and 2) what exactly is "the problem" (what goes wrong) ?

jimaobian commented 7 years ago

Hi @eriknyquist Of course.

  1. The outcome of the sketch I posted should print "hello" every 100ms.
  2. However, if I try to run it on Arduino 101, it doesn't print anything.
  3. If I try to run it on Arduino Uno, it will print "hello" every 100ms.
  4. If I comment the constructor of Class test1 and run it on Arduino 101, it will print "hello" every 100ms.

It seems that the compiler or the linker is not properly worked in this situation.

facchinm commented 7 years ago

Bug confirmed, the sketch works as expected on any other architecture (AVR, SAMD)

eriknyquist commented 7 years ago

Thanks @facchinm and @jimaobian

eriknyquist commented 7 years ago

Assigning to @calvinatintel and @SidLeung to investigate as toolchain issue

intel-larry commented 7 years ago

I'm not sure this is really a good example of a singleton design pattern. I think the issue may be related to the newer C++ standards vs the older ones and the enforcement of publicly declared constructors. (have to think about what's going on here...)

eriknyquist commented 7 years ago

Still trying to figure out what's wrong here-- I had hoped it was symptom of a bug that was fixed here https://github.com/01org/corelibs-arduino101/commit/d6c68f26914bf9508e8b76081d383a5cd432c7b6, but unfortunately not. I should be able to work on this some more next week, I'll post any new information here