gccc-header

C and the <complex.h> file


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

Solution

  • 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.)