the importance of -ansi

Jos van den Oever jvdoever at gmail.com
Fri Jun 15 21:17:15 BST 2007


After a rather long  search for the cause Strigi crash on PPC (e.g.
Mac Mini), I found out that it is a good idea to always use the flag
-ansi when compiling c++ code.

What happened?
Strigi uses CLucene as an index backend. By default it is compiled
without -ansi. Strigi has -ansi as a default flag. This causes a
problem when using the math.h header.
This file, /usr/lib/gcc/powerpc-linux-gnu/4.1.2/include/bits/mathdef.h,
defines the type float_t differently depending on the -ansi flag.

# ifdef __GNUC__
#  if  defined(__STRICT_ANSI__)
typedef float float_t;
typedef double double_t;
#  else
typedef double float_t;
typedef double double_t;
#  endif
# else
typedef double float_t;
typedef double double_t;
# endif

Putting such macro magic in public header files is madness and can
cause nasty bugs. For example, you can have a class like this:

class Planet {
float_t mass;
};

If you new allocate this class with 'new Planet()' you allocate either
4, 8 or 16 bytes depending on your flags and architecture. If this
class is in a library, and you compile the code that uses the library
with different flags than the ones with which you compiled the
library, weird things will happen. Since your objects are smaller or
bigger than you expect you will start writing in the wrong memory
positions when working with the objects.

I just spent quite some time tracking down a bug like this and thought
it worthwhile to tell you about it so you are aware of this issue and
can hopefully fix it faster then I did when you encounter it.

Cheers,
Jos




More information about the kde-core-devel mailing list