简体   繁体   中英

cmath error on MacOS c++17: call to abs ambiguous

Having this error using c++17 on Mac OS. As far as I can tell, code is correct and should work fine (compiles without issue w/ g++ and clang++ on linux). Also, as far as I can tell, the current default mac version of clang [10.0.1] should support c++17 (full version info printout below).

So, my question is: is this actually a bug in my code, but it works by fluke on linux? Or is it an issue with MacOS clang eg, not full c++17 implementation?

From cppref: Defined in header (since C++17): int abs( int n ); Other c++17 features seem to work completely fine.

#include <cmath>
// #include <cstdlib> //works if included
int main() {
  int i = 1;
  // return std::abs(1); // Works fine
  return std::abs(i); // Fails
}

Compile with: clang++ -std=c++17 test.cpp

Get this error:

test.cpp:7:10: error: call to 'abs' is ambiguous
  return std::abs(i);
         ^~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/math.h:761:1: note:
      candidate function
abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
^
(... etc.)
1 error generated.

If you #include <cstdlib> , it works without error. using -std=gnu++17 or -std=c++1z doesn't remove the problem either. In the actual code (which is obviously more complex than the above, and actually uses c++17 features), the error happens depending on the order of my include files. I can't replicate that in the simple example, but I assume it boils down to calling the cstdlib version instead of the cmath version.

Currently, my 'workaround' is to just put the header includes into the order that works..but this is hardly a long-term solution.

Does anyone know the cause?

Version info (error not specific to this MacOS version, also happens on my students' laptops):

Bens-iMac:test ben$ clang++ -v
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

See LWG Issue 2912

This has been fixed in libc++ trunk. I don't know if Apple has shipped this fix yet. As you found, including <cstdlib> is a workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM