Is there any way to get gcc or clang to warn on ex

2019-01-23 19:42发布

问题:

What I'm trying to do is find all explicit casts from type double or float to any other type in some source files I have. Is there a built-in gcc way to do this? Language is C. Thanks!

回答1:

Since casts are explicitly legal, and the right way to perform weird conversions, it's highly unlikely that gcc would contain an option to warn about them

Instead, depending on how huge your source is, you might be able to get away with:

grep '\(double|float\) ' *

to give you all of the double or float variables. Since c isn't a regular language, it's not trivial (with shell tools) to parse this into a list of double or float variables, but if your source is small enough, doing this by hand is easy.

grep '([^()]*)[ ()]*\(your list of variable names\)' *

From there would show you many of your casts.



回答2:

If your C code can also be compiled in C++ mode, you can use g++'s -Wold-style-cast warning flag to trigger a warning on all such casts.

You can determine whether Clang has any warnings which will trigger for a particular coding pattern by using its -Weverything switch (but note that this is not useful for almost any other purpose -- clang has disabled-by-default warnings which trigger on various forms of legitimate code). However, in this case, clang does not have any warnings which trigger on such casts.



回答3:

-Wconversion warn for implicit conversions that may alter a value (double are large types) , and -Wno-sign-conversion disable warnings about conversions between signed and unsigned integers (so there would be less unnecessary warnings). Else I don't see any standard alternative...

Worst case you can looking for those keywords directly into your source files...



回答4:

While the compilers I know don't have options for that, Gimpel's FlexeLint can do what you want:

$ cat tst.c
int main (void)
{
    int i = 0, j = 0;
    float f = 0.0;
    double d = 0.0;

    i = (int) f;
    j = (int) d;
    d = (double) f;
    f = (float) d;
    i = (int)j;
    j = (unsigned) i;
    return (int) j;
}

$ flexelint -w1 +e922 tst.c
FlexeLint for C/C++ (Unix) Vers. 9.00j, Copyright Gimpel Software 1985-2012

--- Module:   tst.c (C)
               _
    i = (int) f;
tst.c  7  Note 922: cast from float to int
               _
    j = (int) d;
tst.c  8  Note 922: cast from double to int
                  _
    d = (double) f;
tst.c  9  Note 922: cast from float to double
                 _
    f = (float) d;
tst.c  10  Note 922: cast from double to float

shell returned 4


回答5:

Well I think there is no such option. After all, a warning is issued by the compiler in order to warn you from things you might have done unintentionally. An explicit cast, however, is basically a way to tell your compiler "shut up, I know what I am doing".