0
votes

The following code compiles on other systems, but not on my Ubuntu 12.04 64bit guest in Virtualbox 4.3.10 on a Windows 7 64bit host.

hello.c

#include "header.h"

int main(int argc, char *argv[]){
    int i;
    for(i=0; i<argc; i++)
        printf("%s\n", argv[i]);
    double x;
        x = testfunction();
    printf("%f \n", x);
    return 0;
}

hello2.c

#include "header.h"

double testfunction ()
{
int i = 1;
double j = 0;
for(i=0; i<1000000; i++)
    j += sin(i/M_PI);
return j;
}

header.h

#include <math.h>
#include <stdio.h>

double testfunction();

When I attempt to compile using

gcc -lm -o hello hello.c hello2.c

I receive the error

/tmp/ccirukEU.o: In function testfunction': hello2.c:(.text+0x33): undefined reference tosin' collect2: ld returned 1 exit status

The error remains even if I include math.h directly in hello2.c. Calculating sin(2/M_Pi) rather than sin(i/M_Pi) removes the error, possibly because gcc then works out the sine itself rather than using the math library.

1

1 Answers

1
votes

Use -lm in the end, as in:

gcc -o hello hello.c hello2.c -lm

This ensures that the linker can realize that there are dependencies missing. Using -lm in the beginning is known to raise problems, because by the time the linker looks at the math library, it hasn't looked at your code yet, so there are no dependencies unresolved.