0

I need a complex library for some stuf in c++ or c.

So I found some useful tooltip in linux.

man complex 

documentation have good example like this:

#include <math.h>        /* for atan */
#include <stdio.h>
#include <complex.h>

int
main(void)
{
   double pi = 4 * atan(1.0);
   double complex z = cexp(I * pi);
   printf("%f + %f * i\n", creal(z), cimag(z));
}

everything goes well...

But I took error every time which I tried.

> Executing task: /usr/bin/g++ -g '/home/max/Documents/c_expls/test2.cpp' -o '/home/max/Documents/c_expls/test2' <

/home/max/Documents/c_expls/test2.cpp: In function ‘int main()’:
/home/max/Documents/c_expls/test2.cpp:10:17: error: expected initializer before ‘z’
   10 |  double complex z = cexp(I * pi);
      |                 ^
/home/max/Documents/c_expls/test2.cpp:11:32: error: ‘z’ was not declared in this scope
   11 |  printf("%f + %f * i\n", creal(z), cimag(z));
      |                                ^
The terminal process "/bin/bash '-c', '/usr/bin/g++ -g '/home/max/Documents/c_expls/test2.cpp' -o '/home/max/Documents/c_expls/test2''" terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

I edited code a little bit, like adding double complex z etc.. but same machine... same error...

I think my gcc installation have lacks component. beause I tried Code::Blocks

Do you have an idea, why my gcc doesn't know this declaration?

maxemilian
  • 347
  • 1
  • 3
  • 15

2 Answers2

3

You need to compile with gcc and specify that you want to use the C99 standard or higher -std=c99.

For C++, use std::complex.

  • Thanks for ans. I apricieted.Yeah I am trying some combinations of declaration almos none of them working except '__complex__ double z' it is only accept this type of decleration. _using namespace std::complex_literals; std::complex z;_ btw I checked with 'gcc -std=c17 test2.c -o test2' but gives error which 'test2.c:(.text+0x37): undefined reference to `cexp'' – maxemilian Nov 01 '20 at 12:14
  • 1
    @maxemilian: Add `-lm` to the end of your command line to link the math library. See https://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c. This is also noted on the Linux man page for `cexp`. When using this, your code compiles and runs just fine for me. – Nate Eldredge Nov 03 '20 at 00:26
1

You need to link against the math library with the flag -lm

Using exactly your code in a file called test.c I compiled with:

gcc -o test test.c -lm

Running the binary gives the output:

./test
-1.000000 + 0.000000 * i
Nathan Wride
  • 965
  • 1
  • 7
  • 28