1

I noticed that when I use sin inside function the compiler don't recognize it, here is an example:

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

float sinus(float a){
    return sin(a);}

int main(int argc, char **argv)
{
    double a = sinus(2);
    printf("%f \n", sin(2));
    printf("%f", a);
    return 0;
}

If I use it directly in main it works fine, but inside a user defined function it gives me this error undefined reference to sin.

For compiling I use gcc -Wall -lm -lc -lgcc -o "%e" "%f".

alk
  • 69,737
  • 10
  • 105
  • 255
  • 1
    What system/environment are you building for? Adding `-lc` and `-lgcc` is almost certainly not necessary... What are `%e` and `%f`? – Carl Norum Dec 27 '19 at 17:14
  • I'm using geany in ubuntu and this is the gcc version `gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) ` `%e` is for the filename without .c and `%f` is for the filename.c – Anas BELFADIL Dec 27 '19 at 17:17
  • Then @alk's comment is what you're looking for (he/she should write it as an answer). – Carl Norum Dec 27 '19 at 17:17
  • Thank you all for your comments. putting the references to libraries in the end resolved it. Happy holidays for you all! – Anas BELFADIL Dec 27 '19 at 17:19
  • @AnasBELFADIL See [what to do when someone answers](https://stackoverflow.com/help/someone-answers). Don't post "thanks", just accept the correct answer with a check mark (when SO allows you to do so). – ggorlen Dec 27 '19 at 17:20

1 Answers1

6

References to libraries typically go to the end of the command line, in particular after the sources have been specified:

gcc -Wall -o "%e" "%f" -lm 

(specifing the C lib is not necessary, it is linked implicilty)

From the documentation:

-l library

[...]

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded.

alk
  • 69,737
  • 10
  • 105
  • 255