在 gcc 中使用内置函数 __builtin_add_overflow_p

Using the builtin function __builtin_add_overflow_p in gcc

我想知道如何使用这个功能,因为我这样做时出现错误:

#define INT_ADD_OVERFLOW_P(a, b) \
__builtin_add_overflow_p (a, b, (__typeof__ ((a) + (b))) 0);
#include <stdio.h>
#include <assert.h>
__int main()
{
    int x1 = -1073741826;
    int y1 = -1073741826;
    int z1 = x1+y1; 
    INT_ADD_OVERFLOW_P ( x1,  y1);
    printf("%d\n",z1);
    return 0;
}

Compile_OUTPUT:

gcc -c -Wall -D DEBUG  tempFile.c
gcc tempFile.o -o tempFile
Makefile:8: recipe for target 'tempFile' failed//new error after update

Compile_ERROR:

tempFile.c: In function ‘main’:
tempFile.c:10:1: warning: implicit declaration of function        ‘__builtin_add_overflow_p’ [-Wimplicit-function-declaration]
tempFile.o: In function `main':
tempFile.c:(.text+0x44): undefined reference to `__builtin_add_overflow_p'
collect2: ld returned 1 exit status
make: *** [tempFile] Error 1

这里是 link 我想使用的函数:

https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html

这是我正在使用的 makefile:

compiler=gcc
CFLAGS=-c -Wall -D DEBUG 
programname=tempFile

all: $(programname)

$(programname): $(programname).o
    $(compiler) $(programname).o -o $(programname)

$(programname).o: $(programname).c
    $(compiler) $(CFLAGS) $(programname).c

clean:
    rm *o $(programname)

所以我想出了如何使用内置函数。我没有使用 __builtin_add_overflow_p,而是使用了 __builtin_add_overflow

#include <stdio.h>
#include <assert.h>

int main(void)
{
  int x1 = -1073741826;
  int y1 = -1073741826;
  int z1 = x1 + y1; 
  int temp;

  printf("%d\n", __builtin_add_overflow(x1, y1, &temp));
  if (__builtin_add_overflow(x1, y1, &temp)) {
    printf("overflow detected");
  }
  printf("%d\n", z1);

  return 0;
}

__builtin_add_overflow_p 支持尚未发布的 GCC 7