Is there any reason to use C instead of C++ for embedded development?

后端 未结 30 3678
既然无缘
既然无缘 2020-11-30 17:20

Question

I have two compilers on my hardware C++ and C89

I\'m thinking about using C++ with classes but without polymorphism (to avoid vtables). The main r

30条回答
  •  清歌不尽
    2020-11-30 17:52

    My personal preference is C because :

    • I know what every line of code is doing (and costs)
    • I don't know C++ well enough to know what every line of code is doing (and costs)

    Why do people say this? You don't know what every line of C is doing unless you check the asm output. Same goes for C++.

    For example, what asm does this innocent statement produce:

    a[i] = b[j] * c[k];
    

    It looks fairly innocent, but a gcc based compiler produces this asm for an 8-bit micro

    CLRF 0x1f, ACCESS
    RLCF 0xfdb, W, ACCESS
    ANDLW 0xfe
    RLCF 0x1f, F, ACCESS
    MOVWF 0x1e, ACCESS
    MOVLW 0xf9
    MOVF 0xfdb, W, ACCESS
    ADDWF 0x1e, W, ACCESS
    MOVWF 0xfe9, ACCESS
    MOVLW 0xfa
    MOVF 0xfdb, W, ACCESS
    ADDWFC 0x1f, W, ACCESS
    MOVWF 0xfea, ACCESS
    MOVFF 0xfee, 0x1c
    NOP
    MOVFF 0xfef, 0x1d
    NOP
    MOVLW 0x1
    CLRF 0x1b, ACCESS
    RLCF 0xfdb, W, ACCESS
    ANDLW 0xfe
    RLCF 0x1b, F, ACCESS
    MOVWF 0x1a, ACCESS
    MOVLW 0xfb
    MOVF 0xfdb, W, ACCESS
    ADDWF 0x1a, W, ACCESS
    MOVWF 0xfe9, ACCESS
    MOVLW 0xfc
    MOVF 0xfdb, W, ACCESS
    ADDWFC 0x1b, W, ACCESS
    MOVWF 0xfea, ACCESS
    MOVFF 0xfee, 0x18
    NOP
    MOVFF 0xfef, 0x19
    NOP
    MOVFF 0x18, 0x8
    NOP
    MOVFF 0x19, 0x9
    NOP
    MOVFF 0x1c, 0xd
    NOP
    MOVFF 0x1d, 0xe
    NOP
    CALL 0x2142, 0
    NOP
    MOVFF 0x6, 0x16
    NOP
    MOVFF 0x7, 0x17
    NOP
    CLRF 0x15, ACCESS
    RLCF 0xfdf, W, ACCESS
    ANDLW 0xfe
    RLCF 0x15, F, ACCESS
    MOVWF 0x14, ACCESS
    MOVLW 0xfd
    MOVF 0xfdb, W, ACCESS
    ADDWF 0x14, W, ACCESS
    MOVWF 0xfe9, ACCESS
    MOVLW 0xfe
    MOVF 0xfdb, W, ACCESS
    ADDWFC 0x15, W, ACCESS
    MOVWF 0xfea, ACCESS
    MOVFF 0x16, 0xfee
    NOP
    MOVFF 0x17, 0xfed
    NOP
    

    The number of instructions produced depends massively on:

    • The sizes of a, b, and c.
    • whether those pointers are stored on the stack or are global
    • whether i, j and k are on the stack or are global

    This is especially true in the tiny embedded world, where processors are just not set up to handle C. So my answer would be that C and C++ are just as bad as each other, unless you always examine the asm output, in which case they are just as good as each other.

    Hugo

提交回复
热议问题