Analyze simple source file

Clang-Tidy can be used to analyze only a source file if only a quick result is needed.

Let us create the following simple C function which is written into myFunction.c source file.

int myFunction(int *alpha, int beta)
{
  beta |= 1 << 32;
  *alpha = beta;
}

In order to highlight the benefits of using Clang-Tidy compared to normal compilation warnings firstly compile the source file:

clang -c myFunction.c -Wall

2 warnings will be shown:

  • warning: shift count >= width of type [-Wshift-count-overflow]

  • warning: non-void function does not return a value [-Wreturn-type]

If we use the static analyzer the number of warnings will be 6

clang-tidy myFunction.c -checks=*,clang-analyzer-*
  • warning: use of a signed integer operand with a binary bitwise operator [hicpp-signed-bitwise] - beta |= 1 << 32;

  • warning: use of a signed integer operand with a binary bitwise operator [hicpp-signed-bitwise] - beta |= 1 << 32;

  • warning: The result of the left shift is undefined due to shifting by '32', which is greater or equal to the width of type 'int' [clang-analyzer-core.UndefinedBinaryOperatorResult]

  • warning: shift count >= width of type [clang-diagnostic-shift-count-overflow]

  • warning: 32 is a magic number; consider replacing it with a named constant [cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers]

  • warning: non-void function does not return a value [clang-diagnostic-return-type]

Based on the warnings the corrected code is shown below.

#include <stdint.h>

#define SHIFT_BITPOS_31     31U

void myFunction(uint32_t * alpha, uint32_t beta)
{
    beta |= (1U << SHIFT_BITPOS_31);
    *alpha = beta;
}

Remark: Although no warnings are shown, the clang-tidy reports that no compilation database is found, configuring the database is described in the following section.