Port C code containing complex numbers to C++ -
the code below runs fine in c. in c++ (std-c++00), compilation fails.
#include <complex.h> int main() { float complex = 0.0; return 0; } here's errors facing
error: complex not pat of 'std' error: expected ';' before i have read solution problem facing here, , aware of std::complex.
but problem that, must port enormous amount of c code c++, complex numbers declared , used, shown above.
so way of ?
what other options have ?
the c99 complex number syntax not supported in c++, instead includes type std::complex in c++ standard library. don't motivation porting code there may couple different things can do.
std::complex specified in c++11 layout compatible c99's complex. implementations of earlier versions of c++ happen provide std::complex layout compatibility well. may able use avoid having port of code. declare c code's interface in c++ such c++ code can linked c implementation.
#include <complex.h> #ifdef __cplusplus extern "c" void foo(std::complex<float>); #else void foo(complex float); #endif you may need modify above implementation. have ensure both name mangling , calling conventions consistent between 2 declarations.
alternatively, there compilers support c complex syntax in c++ extension. of course since c complex macro interfere std::complex macro not defined in c++ , instead have use raw c keyword _complex. or if don't use std::complex anywhere , you're never going define macro yourself: #define complex _complex.
#ifdef __cplusplus #define complex _complex #else #include <complex.h> #endif int main() { float complex = 0.0; return 0; } this #define prohibits use of c++ complex headers. (and technically causes undefined behavior if make use @ of standard library, long avoid headers <complex>, <ccomplex>, , <complex.h> okay in practice.
if need port entire codebase standard c++, might consider porting not directly idiomatic c++, instead 'portable' c. i.e. code compiles both c , c++. way can continue building c while incrementally port , verify continues work correctly throughout porting process.
to you'll things replace float complex typedef , define typedef appropriately in each language, use c header <tgmath.h>, define other macros in c correspond c++ complex interface, etc.
#include <complex.h> #include <math.h> #ifdef __cplusplus using my_complex_type = std::complex<float>; #else #include <tgmath.h> typedef float complex my_complex_type; #define real creal #define imag cimag #endif #define pri_complex_elem "f" void print_sine(my_complex_type x) { x = sin(x); printf("%" pri_complex_elem "+%" pri_complex_elem "i\n", real(x), imag(x)); }
Comments
Post a Comment