Why are drivers and firmwares almost always written in C or ASM and not C++?

后端 未结 15 2279
庸人自扰
庸人自扰 2020-12-14 00:22

I am just curious why drivers and firmwares almost always are written in C or Assembly, and not C++?

I have heard that there is a technical reason for this.

相关标签:
15条回答
  • 2020-12-14 00:57

    Except for wider tool support and hardware portability, I don't think there's a compelling reason to limit yourself to C anymore. I often see complicated hand-coded stuff done in C that can be more naturally done in C++:

    • The grouping into "modules" of functions (non-general purpose) that work only on the same data structure (often called "object") -> Use C++ classes.
    • Use of a "handle" pointer so that module functions can work with "instances" of data structures -> Use C++ classes.
    • File scope static functions that are not part of a module's API -> C++ private member functions, anonymous namespaces, or "detail" namespaces.
    • Use of function-like macros -> C++ templates and inline/constexpr functions
    • Different runtime behavior depending on a type ID with either hand-made vtable ("descriptor") or dispatched with a switch statement -> C++ polymorphism
    • Error-prone pointer arithmetic for marshalling/demarshalling data from/to a communications port, or use of non-portable structures -> C++ stream concept (not necessarily std::iostream)
    • Prefixing the hell out of everything to avoid name clashes: C++ namespaces
    • Macros as compile-time constants -> C++11 constexpr constants
    • Forgetting to close resources before handles go out of scope -> C++ RAII

    None of the C++ features described above cost more than the hand-written C implementations. I'm probably missing some more. I think the inertia of C in this area has more to do with C being mostly used.

    Of course, you may not be able to use STL liberally (or at all) in a constrained environment, but that doesn't mean you can't use C++ as a "better C".

    0 讨论(0)
  • 2020-12-14 00:58

    because from system level, drivers need to control every bits of every bytes of the memory, other higher language cannot do that, or cannot do that natively, only C/Asm achieve~

    0 讨论(0)
  • 2020-12-14 00:59

    There are many style of programming such as procedural, functional, object oriented etc. Object oriented programming is more suited for modeling real world.

    I would use object-oriented for device drivers if it suites it. But, most of the time when you programming device drivers, you would not need the advantages provided by c++ such as, abstraction, polymorphism, code reuse etc.

    0 讨论(0)
提交回复
热议问题