Domanda

In my microcontroller project I have a function for updating CRC (_crc_ibutton_update from avr-libc). The protocol I'm implementing calculates a checksum of a packet including its initial sync byte and I'd like to keep the value of the sync byte's CRC as a compile time constant, but I don't like to precalculate it manually.

Is there a way to force the compiler (GCC 4.3.3) to calculate the value during compile time and emmit only a single load constant instruction?

The function in the library contains only inline assembler, so I've tried using a C implementation when the arguments are constants (determined using __builtin_constant_p() ). The code just gets compiled normally. The CRC function is not too complex, contains only one for loop with constant number of iterations, one branch and a few bitwise operations.

Just to be clear, saving those eight assembler instructions is definitely not critical, but finding some sort of solution to this will be a nice christmas gift for my OCD :-)

È stato utile?

Soluzione

If I declare the function behind the hyperlink in your question static inline, then gcc -O3 compiles the call to the function on known arguments to a single instruction:

~ $ cat t.c
#include <stdint.h>

static inline uint8_t
 _crc_ibutton_update(uint8_t crc, uint8_t data)
{
  uint8_t i;

  crc = crc ^ data;
  for (i = 0; i < 8; i++)
    {
      if (crc & 0x01)
    crc = (crc >> 1) ^ 0x8C;
      else
    crc >>= 1;
    }

  return crc;
}

int x;

int main()
{
  x = _crc_ibutton_update(17, 42);
}
~ $ gcc -O2 -S t.c
~ $ cat t.s
...
    movq    _x@GOTPCREL(%rip), %rax
    movl    $158, (%rax)
    popq    %rbp
    ret
...

This is with “gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)”, and it also works with “gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)” (then requiring -O3).

Altri suggerimenti

There is a way, but you have to upgrade to C++11!

the new constexpr specifier is exactly what you look at. But for sad, it is not supported in GCC 4.3.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top