1

I have been developing a set of software drivers for the peripherals of a MCU. I need to implement those drivers in the C++ programming language. My idea was to model each driver by its own class.

Interface of a driver for the Peripheral01:

#include "HalCfg.h" class Periph01 { public: Periph01(HalCfg*); Periph01(const Periph01& orig); virtual ~Periph01(); void init(); int getCfg(); private: HalCfg *m_halCfg; int m_cfg; }; 

Implementation of a driver for the Peripheral01:

#include "Periph01.h" Periph01::Periph01(HalCfg *halCfg) { m_halCfg = halCfg; } Periph01::Periph01(const Periph01& orig) { } Periph01::~Periph01() { } void Periph01::init() { m_cfg = m_halCfg->periph01Cfg.cfg; } int Periph01::getCfg() { return m_cfg; } 

Each driver will have its configuration

struct Periph01Cfg { int cfg; }; 

Configuration of all the drivers will be aggregated at one place

#include "Periph01Cfg.h" struct HalCfg { Periph01Cfg periph01Cfg; }; 

The usage will be following

int main(int argc, char** argv) { HalCfg halCfg; halCfg.periph01Cfg.cfg = 255; Periph01 periph01 = Periph01(&halCfg); periph01.init(); cout << "Peripheral_01 configuration: " << periph01.getCfg() << endl; return 0; } 

The weakness of this solution is that I need to define a HalCfg type variable and then fill the configuration of all the peripherals at run time. From my point of view it would be better if I can fill the configuration of all the peripherals at compile time at one place in the software. Does anybody have any idea how to do that? Thanks in advance.

UPDATE:

I have probably find a solution based on the so called in-class initialization:

Configuration of all the drivers will be aggregated at one place

#include "Periph01Cfg.h" struct HalCfg { Periph01Cfg periph01Cfg = {255}; }; 

The usage will be following

int main(int argc, char** argv) { HalCfg halCfg; Periph01 periph01 = Periph01(&halCfg); periph01.init(); cout << "Peripheral_01 configuration: " << periph01.getCfg() << endl; return 0; } 
3
  • please don't cross-post: stackoverflow.com/questions/64842880/… "Cross-posting is frowned upon as it leads to fragmented answers splattered all over the network..." Commented Nov 15, 2020 at 10:11
  • @gnat I advised the OP to ask here. The original question should be deleted though. Commented Nov 15, 2020 at 10:20
  • @πάνταῥεῖ I have probably find a solution of my problem (please see the update in my original post). Please can you tell me what do think about that idea? Commented Nov 15, 2020 at 19:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.