Johann Oskarsson
Johann Oskarsson

Reputation: 816

How do I use C99 complex numbers with clang on Windows?

I have installed Visual Studio 2019 and it comes wih clang. I can successfully compile and link applications with clang.

When I #include <complex.h> however, I do not get standard compliant complex numbers.

Here is an example that does not work after including <complex.h>.

complex float z = 2.0f + 3.0f * I;

It tells me the complex keyword is undeclared.

error: use of undeclared identifier 'complex'

However, I am able to use Microsoft non-standard complex numbers. Here is a complete program that works.

#include <stdio.h>
#include <complex.h>

int main( int argc, char *argv[] ) {
  _Fcomplex z = { 2.0f, 3.0f };

  printf( "z = %f + %f * i\n", crealf( z ), cimagf( z ) ); 
  return 0;
}

And I can compile and link it with clang -m64 -o cmplx.exe cmplx.c. The output is predictably

z = 2.000000 + 3.000000 * i

Can I get standard compliant complex numbers with clang on Windows?

Upvotes: 1

Views: 1580

Answers (1)

Schwern
Schwern

Reputation: 164769

The compiler and the libraries it's using are separate. Even though you're compiling with clang, you're still using Microsoft's non-standard libraries.

The Microsoft implementation of the complex.h header defines these types as equivalents for the C99 standard native complex types:

Standard type                                   Microsoft type
float complex or float _Complex                 _Fcomplex
double complex or double _Complex               _Dcomplex
long double complex or long double _Complex     _Lcomplex

You can smooth some of this over with typdefs and macros, as demonstrated in this answer.

Upvotes: 3

Related Questions