No matter what you do, you cannot correctly handle the "float complex" in a compiler other than C99. So instead of writing this, make a few typedef. This is much simpler if you need to support only one complex type, so I will just demonstrate it with float complex .
First define the types:
#if __STDC_VERSION__ >= 199901L
Then we should be able to create complex numbers and emulate creal and cimag.
if STDC_VERSION >= 199901L
//creal, cimag already defined in complex.h
inline complex_float make_complex_float(float real, float imag) { return real + imag * I; }
else
define creal(z) ((z).re)
define cimag(z) ((z).im)
extern const complex_float complex_i; //put in a translation unit somewhere
define I complex_i
inline complex_float make_complex_float(float real, float imag) { complex_float z = {real, imag}; return z; }
endif
Next, write functions that wrap addition, subtraction, multiplication, division, and comparisons.
#if __STDC_VERSION__ >= 199901L
Note that `add_complex (c, 5)` does not work in C89 mode in the above code, because the compiler does not know how to make 5 into complex. This is a difficult problem to fix in C without compiler support - you need to resort to tricks, such as the new `tgmath.h`, which are specific to the compiler.
Unfortunately, the effect of all this is that a nice C99 syntax, such as `a + b` to add complex numbers, should be written` add_complex (a, b) `.
Another option (as another poster pointed out) is to use C ++ `std :: complex` for compilers other than C99. It might be OK if you can wrap things in typedefs and `# ifdef`s. However, you will need either C ++ or C99.