Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ <complex> and <complex.h> in the same file

Tags:

c++

gcc

I have a large code base that uses the c++ <complex> header and many std::complex<double> objects. But now I also want to use a couple other libraries (fftw and spinsfast) that use <complex.h>. Unfortunately, mixing these two types of complex seems to be incompatible with gcc 4.6.1 (presumably among others).

Here's a minimal working example showing the error:

// This is what I do for my various complex objects
#include <complex>

// This is one of many things FFTW/spinsfast essentially do
extern "C" {
  #include <complex.h>
}

int main() {
  std::complex<double>(1.0,2.0);
  return 0;
}

And when I compile:

> g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:7:8: error: expected unqualified-id before ‘_Complex’
test.cpp:7:8: error: expected ‘;’ before ‘_Complex’

Evidently, gcc is translating std::complex<double> into _Complex, which somehow is also undefined. [This works fine on my macbook, which uses Apple LLVM version 5.1; this compiler error is happening on a cluster that I need to support.]

I can't even figure out where this is coming from; none of the include files in my gcc installation have "_Complex" -- though they do have "_ComplexT". How do I debug this kind of thing?

Or more helpfully, how do I solve this compiler error in a way that will work for more than just a small slice of gccs?

like image 485
Mike Avatar asked May 01 '14 18:05

Mike


1 Answers

In C, _Complex is a keyword used to declare complex numbers: float _Complex. However, they #define complex _Complex so you can write float complex which looks nicer.

Of course, you get in trouble when using the name complex in a context other than where you want _Complex, such as std::complex, which then expands to std::_Complex.

So if you use <complex> in C++, you should get rid of this macro:

#include <complex.h>
#undef complex

That's actually what g++ does since 4.8 to support both <complex> and <complex.h> in the same translation unit.

Note that when enabling C++11, you won't get the error either.

like image 161
leemes Avatar answered Oct 12 '22 10:10

leemes