Search code examples
javac++device-driverdrivers

What is the advantage of c++ in writing device drivers?


As I know in order to write device drivers people usually use c++ or assembly? The choice of assembly is clear for me. But why c++? I guess it is possible to do in java (for example), or in other high level language as well. So why c++ is so common? Is there a specific feature of C++ programming language that is necessary for writing drivers?


Solution

  • I would say that C is much more commonly used as a language for device drivers (over C++).

    There are a couple of reasons for this:

    1. Most of the major operating systems are written in a combination of C and assembler and provide C language interfaces to the operating system.
    2. Writing a device driver usually involves communicating with a device which involves direct memory manipulation of registers and the like. C and C++ allow you to do this natively.

    Edit - Example of Direct Memory Manipulation:

    Let me make up some fictitious device. Say it has a register, that when you write certain values onto it, makes a light on the device turn on. This register is 32 bits wide. The top 31 bits say how bright to make the light, the lowest bit turns it on and off.

    When you plug the device into the computer, the operating system assigns that register a particular memory location, (let's say 0x00FF00FF00 on a 32 bit OS). In order to turn the light on, the device driver would do something like this:

    int* lightRegister = 0x00FF00FF00; // You would normally ask the OS for this address, not hardcode it.
    int brightnessValue = 256; // Only Even numbers, the low bit must be zero.
    *lightRegister = brightnessValue | 1; //Turn it on.
    *lightRegister = 0; // Turn it off.
    

    Higher level languages like Java, don't generally let you write into some random memory location like this.