0

My simple program compTest.c

#include<stdio.h>
#include<complex.h>

int main(void)
{
    double complex z = 1.0 + 1.0 * I;

    printf("|z| = %.4f\n", cabs(z));

    return 0;
 }

When using the standard library and compiling with gcc on a Linux system do I need to include the -lm flag for it to work?

Example:

gcc -o executableName fileName.c -lm

When I don't I get the following: /tmp/cc1o7rtt.o: In function `main':

comTest.c:(.text+0x35): undefined reference to `cabs'
collect2: error: ld returned 1 exit status
Jay
  • 75
  • 1
  • 9

1 Answers1

2

It seems that you've already discovered that the answer is yes.

The -lm flag tells the linker to link the math library, which contains, among other things, the code for the cabs function. (This is a gcc/Linux issue, not a C language issue.)

The Linux man page for cabs specifically says Link with -lm.

(In general, if you want to call any library function and you're not 100% certain how to use it, read the man page.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • I read the man page but I seemed to have missed the part where it says "Link with -lm'. The first place I always go is to the man page. Then Google. Then if I can't find something remotely similar I come here. Thanks for the info. – Jay Feb 16 '19 at 01:38