www.digitalmars.com         C & C++   DMDScript  

c++ - Code generation bug in mixing C and C++ in returning structs

reply Burton Radons <burton.radons gmail.com> writes:
Say I have this header file, "a.h":

  typedef struct S S;

  struct S
  {
    int a;
    int b;

  #ifdef CPP_CONSTRUCTOR
  #ifdef __cplusplus
    S () : a (0), b (0) { }
  #endif
  #endif
  };

  #ifdef __cplusplus
  extern "C"
  #endif
  S f ();

I also have this C file, "b.c":

  #include "a.h"

  #ifdef __cplusplus
  extern "C"
  #endif
  S f ()
  {
    S result;
    result.a = result.b = 100;
    return result;
  }

Finally I have this C++ file, "c.cpp":

  #include "a.h"
  #include <stdio.h>

  int main ()
  {
    S t = f ();
    printf ("%d %d\n", t.a, t.b);
    return 0;
  }

Then I compile it with "sc b.c c.cpp -DCPP_CONSTRUCTOR a.exe". When executing
the file I would expect it to print "100 100". Instead it prints garbage.

If I instead compile it with "sc b.c c.cpp a.exe" (causing the constructor in
S to be not present), it prints "100 100" as it should.

The reason is that in the latter case without the constructor it expects the
return value to be in EAX EDX, as it actually is returned from f. In the
former case it passes a return pointer in EAX, which of course isn't written
with anything so it reports whatever was on the stack beforehand. Note that
b.c is being compiled correctly, so it's not dependent on build process but
only the presence of the constructor. Other methods in the structure don't
have an effect, just the constructor.

Does anyone know of a workaround?
Oct 10 2009
parent Walter Bright <newshound1 digitalmars.com> writes:
I added it to bugzilla:

http://bugzilla.digitalmars.com/issues/show_bug.cgi?id=44
Oct 10 2009