2

How can I make gcc (6.3) to warn for all explicit 64bit to 32bit conversions done by casting (C code)?

  • Explicit conversions are ignored by -Wconversion flag.
  • I'm about to compile a very big and old project to 64bit and I know that there are many programmers misuses of casting and it is impossible to find all of them manually.
  • Parsing the code is not enough due to many custom definitions and structs which holds the parameters, it has to be at the compilation stage.

e.g. How can i find this type of issues automatically?

typedef long long my_type;
int foo()
{
  my_type f;
  ...
  return (int)f;
}

struct stat {
  ino_t st_ino;    /* 64bit Inode number */
... };

int foo2(){
  stat s;
  ...
  return (int)s.st_ino;
{
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
IdolAdmin
  • 61
  • 1
  • 5
  • 8
    C or C++? Yes, the answer can actually differ. – StoryTeller - Unslander Monica Feb 12 '18 at 13:49
  • Unfortunately, casts in C tend to silence a lot of potentially dangerous behaviors. That's one reason that casts should be generally avoided. – Jonathon Reinhart Feb 12 '18 at 13:51
  • 2
    If you intend to use C++ you might go all the way and use [clang-tidy + cppcoreguidelines-pro-type-cstyle-cast](https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-cstyle-cast.html) to get a list of all the casts and fix them one by one. You can probably get clang to list all 32 to 64 bit conversions, but that might take a bit of work. – nwp Feb 12 '18 at 13:54
  • `-Wnarrowing` may help you. Also maybe [clang tidy](http://clang.llvm.org/extra/clang-tidy/). – Jesper Juhl Feb 12 '18 at 14:06
  • In c++ can't you set `my_type::operator int() = delete;` (deleted? removed? something like that). Doesn't help with system types like ino_t though. – Goswin von Brederlow Feb 12 '18 at 14:09
  • Try `-Wold-style-cast` and replace them with new style casts obviously checking as you go. – Richard Critten Feb 12 '18 at 14:09
  • I'm compiling c with gcc (6.3) – IdolAdmin Feb 12 '18 at 18:16
  • The only solution that I can think of is customize gcc to warn about any assigment from 64bit to 32bit. Do you have suggestions how to do so? Where do i start? – IdolAdmin Feb 12 '18 at 18:20

0 Answers0