GCC function name conflict

前端 未结 3 1221
盖世英雄少女心
盖世英雄少女心 2021-01-13 06:43

I was having some problems with a sample code i was testing, since my abs function was not returning the correct result. abs(-2) was outputing -2 (this, by the way, is supos

相关标签:
3条回答
  • 2021-01-13 06:55

    gcc optimizes the call to abs() to use its built-in abs(). So if you use the -fno-builtin option (or define your abs() as returning int), you'll notice you get the correct result. According to this (quoting):

    GCC includes built-in versions of many of the functions in the standard C library. The versions prefixed with _builtin will always be treated as having the same meaning as the C library function even if you specify the -fno-builtin option. (see C Dialect Options) Many of these functions are only optimized in certain cases; if they are not optimized in a particular case, a call to the library function will be emitted.

    Had you included stdlib.h, which declares abs() in the first place, you'd get an error at compile time.

    0 讨论(0)
  • 2021-01-13 07:13

    Sounds a lot like this bug, which is from 2007 and noted as being fixed.

    You should of course try to compile without GCC's intrinics, i.e. pass -fno-builtin (or just -fno-builtin-abs to snipe out only abs()) when compiling.

    0 讨论(0)
  • 2021-01-13 07:14

    GCC is playing tricks on you due to the interplay of the following:

    • abs is a built-in function;
    • you're declaring abs to return unsigned int while the standard (and built-in) abs returns signed int.

    Try compiling with gcc -fno-builtin; on my box, that gives the expected result of 1. Compiling without that option but with abs declared as returning signed int causes the program to print 2.

    (The real solution to this problem is to not use library identifiers for your own functions. Also note that you shouldn't be printing an unsigned int with %d.)

    0 讨论(0)
提交回复
热议问题