1

I have the following two functions and when compiling, I am face with the error in the title.

double getIdf(FileList fl, int D){
  double fileCount = countFiles(fl); //todo countfiles
  double temp = fileCount/D;
  double idf = log10(temp);
  return (fabs(idf));
}

double countFiles(FileList fl){
    if (fl == NULL){
        printf("countFiles FL does not exist\n");
        return 0;
    }
    double count = 0;
    FileList curr = fl;
    while (curr != NULL) {
        count++;
        curr = curr->next;
    }
    return count;
}

However, if I change the log10 function to log10(5.5) it would work.

double getIdf(FileList fl, int D){
  double fileCount = countFiles(fl); //todo countfiles
  double temp = fileCount/D;
  double idf = log10(5.5);
  return (fabs(idf));
}

I am compiling with -lm.

Whats wrong here?

REDBEAN
  • 21
  • 5
  • 4
    Post the exact command line you are using to link. If it's like `gcc -lm foo.c`, that is your problem; the `-lm` needs to go at the end. See https://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc – Nate Eldredge Oct 24 '20 at 15:09
  • 1
    The difference in your changed version is likely that when the argument is a constant, the compiler can compute `log10(5.5)` at compile time and not need a call to the library function at all. – Nate Eldredge Oct 24 '20 at 15:11
  • Maybe there are some include files missing? (at least from the code you posted) – wildplasser Oct 24 '20 at 15:13
  • @NateEldredge yes moving -lm to the end worked. Why is that? How do I change the code so that I do not have to move -lm to the back for it to compile? – REDBEAN Oct 24 '20 at 15:18
  • Read the link in my previous comment. – Nate Eldredge Oct 24 '20 at 15:18

1 Answers1

3

You typed

gcc -lm program.c

You want

gcc program.c -lm

Because libraries only pull in symbols that are referenced by the code already being linked in, and you tried to link in the library before adding any code.

I know, it's terrible. It would be nicer if it could index the libraries and use them to reference symbols needed only after the library loads. I've had to reference libraries twice.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • Is there no way to compile with -lm at the front? I'm doing a university project that will go through autotesting. The autotest program will compile with -lm at the front... – REDBEAN Oct 24 '20 at 16:28
  • @REDBEAN: the autotest program shouldn't do that unless it is running on a platform in which the linker scans all libraries. More details about the test environment would be useful (as an edit to your question, not as a comment here ) – rici Oct 24 '20 at 16:37