Type checking in source files

I spent many hours debugging a problem that turned out to be caused by two source files, including two header files in a different order. One of these headers set _FILE_OFFSET_BITS to 64, and the other file header is included <sys / types.h>, which defines off_t as 32 or 64 bits depending on the setting of _FILE_OFFSET_BITS. I have given a brief example of this situation below. This was on x86_32 Linux (both Debian and CentOS 4.8).

Neither gcc -Wall main.c other.c, nor the Solaris 9 lint, nor splint detect this situation.

Does anyone know of a software tool that can detect this situation?

main.c

  #define _FILE_OFFSET_BITS 64
 #include <sys / types.h>
 #include <stdio.h>

 #include "header.h"

 int
 main (int argc, char ** argv) {
         struct foo bar = {(off_t) 0, "foo"};

         showproc (& bar);
         printf ("sizeof (off_t) in main.c is% d \ n", sizeof (off_t));

         return 0;
 }

other.c

  #include <sys / types.h>
 #define _FILE_OFFSET_BITS 64
 #include <stdio.h>

 #include "header.h"

 void
 showproc (const struct foo * p)
 {
         if (p-> offset == 0) {
             if (p-> s == NULL)
                 puts ("NULL pointer reference");
             else
                 printf ("Structure value is% s \ n", p-> s);
         }
         printf ("sizeof (off_t) in other.c is% d \ n", sizeof (off_t));
 }

header.h

  struct foo {
         off_t offset;
         const char * s;
 };

 extern void showproc (const struct foo *);

Program output

  Null pointer reference
 sizeof (off_t) in other.c is 4
 sizeof (off_t) in main.c is 8
+4
source share
2 answers

I would recommend that put determines that it modifies such headers as in the makefile and not in the code. Otherwise, you cannot be sure which compilation units have one definition or another, as you have already experienced.

Sometimes modifying headers with macros is the intended behavior (for example, using headers as templates), and sometimes it is not (for example, in your case), so I think it's hard to create meaningful warnings from the tool.

+4
source

If you need to define something in the header file, make sure that everything that uses it includes that header. This includes other headers.

+2
source

All Articles