【发布时间】:2018-01-04 05:11:31
【问题描述】:
考虑以下程序:
#include <cstdio>
#include <cmath>
int main()
{
int d = (int)(abs(0.6) + 0.5);
printf("%d", d);
return 0;
}
g++ 7.2.0 输出0(见现场演示here)
g++6.3.0(见现场演示here)
prog.cc: In function 'int main()':
prog.cc:6:26: error: 'abs' was not declared in this scope
int d = (int)(abs(0.6) + 0.5);
^
prog.cc:6:26: note: suggested alternative:
In file included from prog.cc:2:0:
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/cmath:103:5: note: 'std::abs'
abs(_Tp __x)
^~~
clang++ 5.0.0 输出1(见现场演示here)
clang++3.6.0(见现场演示here)
prog.cc:6:19: error: use of undeclared identifier 'abs'; did you mean 'fabs'?
int d = (int)(abs(0.6) + 0.5);
^~~
fabs
/usr/include/x86_64-linux-gnu/bits/mathcalls.h:181:14: note: 'fabs' declared here
__MATHCALLX (fabs,, (_Mdouble_ __x), (__const__));
^
/usr/include/math.h:71:26: note: expanded from macro '__MATHCALLX'
__MATHDECLX (_Mdouble_,function,suffix, args, attrib)
^
/usr/include/math.h:73:22: note: expanded from macro '__MATHDECLX'
__MATHDECL_1(type, function,suffix, args) __attribute__ (attrib); \
^
/usr/include/math.h:76:31: note: expanded from macro '__MATHDECL_1'
extern type __MATH_PRECNAME(function,suffix) args __THROW
^
/usr/include/math.h:79:42: note: expanded from macro '__MATH_PRECNAME'
#define __MATH_PRECNAME(name,r) __CONCAT(name,r)
^
/usr/include/x86_64-linux-gnu/sys/cdefs.h:88:23: note: expanded from macro '__CONCAT'
#define __CONCAT(x,y) x ## y
^
1 error generated.
Microsoft VC++ 19.00.23506 输出 1(见现场演示 here)
这个程序到底发生了什么?为什么在不同的 C++ 编译器上编译时会给出不同的输出?为什么即使在同一编译器的不同版本上程序也会表现出不同的行为?这是编译器问题还是标准库(libstdc++ & libc++)问题? C++ 标准对此有何规定?
PS:我知道我需要写std::abs 而不是abs。但这不是我的问题。
【问题讨论】:
-
数学标题远非统一。 g++ 实际上是最不标准的一次,而不是 VS。
标签: c++ language-lawyer libstdc++ c++-standard-library libc++