c++
Using <complex> vs <complex.h> with g++
Posted by HokieTux on February 1, 2010 in Code, Hacks
Long story short: Including <complex.h> in your C++ source file does not include the C language complex.h header!
After fighting with g++ to get the proper complex numbers implementation working in a recent project of mine, I thought I would post what I discovered in case anyone else finds it useful.
It is fairly common knowledge that use of C-style standard headers in C++ is considered deprecated. By this I mean that if you want to include <stdio.h>, a C library, in a C++ source file, then you should actually include <cstdio>. The same exists for other libraries, e.g. <math.h> is <cmath>, <signal.h> is <csignal>, etc. This has been phased into recent versions of compilers with varying levels of enforcement.
However, not all standard C libraries have been moved over to the new standard. For a long while, <stdint.h>, which includes bit-specific datatype declarations like int32_t and uint64_t, did not have an equivalent <cstdint>. In these circumstances, including the originial <stdint.h> worked just fine, and included the C language header as expected.
This is not the case with <complex.h>.
The C++ standard implementation of complex numbers is a templated type. To declare it, you do something like:
complex<float> mynum(2.0, 3.0);
The C version of complex numbers is an IEEE standard (1003.1), and is declared like so:
complex double mynum = {2.0 + 3.0*I}
If you want to use the C version, you might think all you need to do is #include <complex.h> in a C++ file… turns out that doesn’t work. For whatever reason, g++ will include the C++ templated type rather than the standard C language type.
If you want to use the C version, the easiest way I’ve found is to simply give the absolute path to the include header, like so:
#include “/usr/include/complex.h”
I ended up using the C++ version anyways, but while I was attempting to use the C implementation, this one certainly had me confused for a bit.