Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...