简体   繁体   中英

Static C++ members in a micocontroller

I'm writing some C++ code that'll run on a microcontroller. More specifically, the target mcu is a K22 and I'm using NXP's MCUXpresso compiler for that.

I've noticed that static class members are not being initialized at startup. For example, see the code below:

class B {
  public:
  B() { std::cout << "Init B" << std::endl;}
};
class A {
  public:
  static B b;
  static A *instance;
  static A *getInstance() {
    if (!instance) {
      instance = new A;
    }
    return instance;
  }

  private:
  A() {
    std::cout << "Init A" << std::endl;
  }
};

A* A::instance;
B A::b;

int main() {
    return 0;
}

If you build this with no optimizations or whatsoever in a regular Linux target and run it you'll see it'll output Init B , as B is a static member and it's being initialized by the libc startup code.

If I do the same in my K22 mcu, I don't see A::b being initialized at any time. And of course, if I access A::getInstance()->b, b is null.

This is probably a question for the MCUXpresso guys, but is thata common limitation when it comes to C++ on microcontrollers? Maybe I need a specific startup file for C++?

EDIT

Can't copy startup file as it's too big. Anyway I got it for a sample project and it data_init , bss_init sections and the like.

通过将启动文件startup_mk22f51212.c重命名为startup_mk22f51212.cc此问题,以便C ++编译器进行构建。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM