是否存在通过C库而不是通过命名空间std使用符号的GCC警告? [英] Is there a GCC warning for using symbols from the C library not through namespace std?
问题描述
考虑以下(笨拙的)C ++代码:
Consider the following (buggy) C++ code:
#include <cmath>
#include <cstdlib>
#include <iostream>
int main() {
if (abs(-0.75) != 0.75) {
std::cout << "Math is broken!\n";
return 1;
} else {
return 0;
}
}
此代码有错误,因为它调用 abs
(意思是 :: abs
)而不是 std :: abs
.根据实现的不同, :: abs
可能不存在,或者它可能是C abs
,或者它可能是一个过载集,其中包括 double
,例如 std :: abs
是.
This code is buggy because it calls abs
(meaning ::abs
) instead of std::abs
. Depending on the implementation, ::abs
might not exist, or it might be the C abs
, or it might be an overload set including a version for double
, like std::abs
is.
至少在我的环境中,使用Linux上的Clang时,事实证明它是第二个选项:C abs
.即使未显式启用任何警告,这也会引发两个警告:
With Clang on Linux, at least in my environment, it turns out to be the second option: C abs
. This provokes two warnings, even without explicitly enabling any:
<source>:7:9: warning: using integer absolute value function 'abs' when argument is of floating point type [-Wabsolute-value]
if (abs(-0.75) != 0.75) {
^
<source>:7:9: note: use function 'std::abs' instead
if (abs(-0.75) != 0.75) {
^~~
std::abs
<source>:7:13: warning: implicit conversion from 'double' to 'int' changes value from -0.75 to 0 [-Wliteral-conversion]
if (abs(-0.75) != 0.75) {
~~~ ^~~~~
在GCC上,我在不同的环境中得到了不同的结果,但是我还没有弄清楚该环境的哪些细节是相关的.不过,更常见的选择是它也调用C abs
函数.但是,即使使用 -Wall -Wextra -pedantic
,它也不会发出警告.我可以通过 -Wfloat-conversion
强制发出警告,但这会给我的其余代码库带来太多误报(也许我应该解决,但这是另一个问题):
On GCC, I get different results in different environments and I haven’t yet figured out what details of the environment are relevant. The more common option, though, is also that it calls the C abs
function. However, even with -Wall -Wextra -pedantic
, it gives no warnings. I can force a warning with -Wfloat-conversion
, but that gives too many false positives on the rest of my codebase (which perhaps I should fix, but that’s a different issue):
<source>: In function 'int main()':
<source>:7:18: warning: conversion to 'int' alters 'double' constant value [-Wfloat-conversion]
if (abs(-0.75) != 0.75) {
^
当命名空间 std
中的版本超载时,是否有办法通过全局命名空间使用库函数来发出警告?
Is there a way to get a warning whenever I use a library function through the global namespace, when the version in namespace std
is an overload?
推荐答案
这是一个解决方案.我对此不满意,但它可能对您有用:
Here's a solution. I'm not happy with it, but it might work for you:
namespace DontUseGlobalNameSpace {
// put all std functions here you want to catch
int abs(int x);
}
using namespace DontUseGlobalNameSpace;
现在,如果您不加限定地使用 abs()
,则会出现符号不明确"错误.
Now, if you use abs()
without qualification, you'll get a "symbol is ambiguous" error.
这篇关于是否存在通过C库而不是通过命名空间std使用符号的GCC警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!