Visual Studio による C99 複雑なサポート

何をしても、C99 以外のコンパイラで "float complex" を適切に解析することはできません。そのため、それを記述する代わりに、いくつかの typedef を作成します。複合型を 1 つだけサポートすればよいので、float complex で説明します。 .

まず、型を定義します:

#if __STDC_VERSION__ >= 199901L
//using a C99 compiler
#include <complex.h>
typedef float _Complex float_complex;
#else
typedef struct 
{
    float re, im;
} float_complex;
#endif

次に、複素数を作成し、creal と 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

次に、加算、減算、乗算、除算、および比較をラップする関数を記述します。

#if __STDC_VERSION__ >= 199901L
#define add_complex(a, b) ((a)+(b))
//similarly for other operations
#else //not C99
inline float_complex add_complex(float_complex a, float_complex b)
{
  float_complex z = {a.re + b.re, a.im + b.im};
  return z;
}
//similarly for subtract, multiply, divide, and comparison operations.

add_complex(c, 5) に注意してください 上記のコードでは、C89 モードでは機能しません。これは、コンパイラが 5 を複素数にする方法を認識していないためです。これは、コンパイラのサポートなしで C で修正するのが難しい問題です -- 新しい tgmath.h のようなトリックに頼らなければなりません

残念ながら、これらすべての結果として、a+b のような優れた C99 構文は 複素数を加算するには add_complex(a, b) と書かなければなりません .

別のオプション(別のポスターが指摘したように)は、C++ std::complex を使用することです C99 以外のコンパイラで。これは、typedef と #ifdef でラップできれば問題ないかもしれません。 秒。ただし、C++ または C99 が必要です。