gcccastingcompilationcmockery

How do I work around the GCC "error: cast from ‘SourceLocation*’ to ‘int’ loses precision" error when compiling cmockery.c?


I need to add unit tests using Cmockery to an existing build environment that uses as hand-crafted Makefile. So I need to figure out how to build cmockery.c (without automake).

When I run:

g++ -DHAVE_CONFIG_H -DPIC -I ../cmockery-0.1.2 -I /usr/include/malloc -c ../cmockery-0.1.2/cmockery.c -o obj/cmockery.o

I get a long list of errors like this:

../cmockery-0.1.2/cmockery.c: In function ‘void initialize_source_location(SourceLocation*)’:
../cmockery-0.1.2/cmockery.c:248: error: cast from ‘SourceLocation*’ to ‘int’ loses precision

Here are lines 247:248 of cmockery.c:

static void initialize_source_location(SourceLocation * const location) {
    assert_true(location);

assert_true is defined on line 154 of cmockery.h:

#define assert_true(c) _assert_true((int)(c), #c, __FILE__, __LINE__)

So the problem (as the error states) is GCC doesn't like the cast from ‘SourceLocation*’ to ‘int’.

I can build Cmockery using ./configure and make (on Linux, and on Mac OS X if I export CFLAGS=-I/usr/include/malloc first), without any errors. I've tried looking at the command-line that compiles cmockery.c when I run make (after ./configure):

 gcc -DHAVE_CONFIG_H -I. -I. -I./src -I./src -Isrc/google -I/usr/include/malloc -MT libcmockery_la-cmockery.lo -MD -MP -MF .deps/libcmockery_la-cmockery.Tpo -c src/cmockery.c  -fno-common -DPIC -o .libs/libcmockery_la-cmockery.o

...but I don't see any options that might work around this error.

In "error: cast from 'void*' to 'int' loses precision", I see I could change (int) in cmockery.h to (intptr_t). And I've confirmed that works. But since I can build Cmockery with ./configure and make, there must be a way to get it to build without modifying the source.


Solution

  • Using gcc instead of g++ on my system turns that error into a warning on my system (Mandriva Linux 2010.1 64-bit) and allows the compilation to complete:

    .
    .
    .
    ../cmockery-0.1.2/cmockery.c:248: warning: cast from pointer to integer of different size
    .
    .
    .
    

    I feel the need to point out, however, that I am generally wary when I see a whole horde of warnings on what is a relatively common platform (Linux 64-bit/GCC and I would presume others). Using the -m32 option to force compilation to a 32-bit object file does not produce any warnings, so one could presume that the source code used as-is is may not be 64-bit clean. This happens whether you use the autotools or not.

    I don't know the project in question, so it might very well be OK, but in any case use with caution...

    EDIT:

    According to this answer to the OP's question to the cmockery mailing list, the current release is not 64-bit clean at this time. It seems that the errors/warnings were there for a good reason...