I'm trying to hunt down a problem using complex literals when compiling with GCC. Consider the following
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = CMPLX(0.0, -1.0);
printf("z = %.1f%+.1fi\n", creal(z), cimag(z));
return 0;
}
(slightly modified from the reference page). If I compile with Clang, it works as expected. However, if I use GCC I get an undefined reference error
gcc -std=c11 mwe.c
mwe.c: 6:24 warning: implicit declaration of function 'CMPLX' ...
mwe.c:(...) undefined reference to `CMPLX'
I have tried this with GCC 4.7 and 7.2 on Linux and GCC 9 on MacOS. The error messages change, but the net result remains the same. Reviewing the reference for CMPLX
, this should be valid C11. Based on this answer and this post, it appears like GCC accepted this construct before.
My bottom line question is: Why can't I use CMPLX
with GCC?
It appears like this is caused by a header/library disconnect on the systems I have. Compiling with the -save-temps
flag, it appears GCC uses the system header for complex.h
. This means the selected Xcode SDK's usr/include/complex.h
on MacOS and /usr/include/complex.h
on Linux. On MacOS, the CMPLX
macro is only defined when using Clang. The Linux I have is RHEL 6 meaning the header is aimed at GCC 3 which did not have CMPLX
. Based on the discussion on this bug report, it looks like making sure the macro is defined is not up to GCC.
The short answer is: The compiler/platform combination doesn't support it. Use the native compiler or update the system.