2

I want to compile the sample pthread code from http://pages.cs.wisc.edu/~travitch/pthreads_primer.html (Mutex section). As I run this command:

 gcc -pedantic -Wall -o theaded_program pth.c -lpthread 

which is stated in the link, I get this error

pth.c:45:5: warning: ISO C90 forbids mixed declarations and code [-pedantic]
/tmp/ccajksBv.o: In function `opponent':
pth.c:(.text+0x4a): undefined reference to `tan'
/tmp/ccajksBv.o: In function `main':
pth.c:(.text+0x131): undefined reference to `tan'
collect2: ld returned 1 exit status

However #include <math.h> is there in the code!! The gcc version is 4.6

mahmood
  • 23,197
  • 49
  • 147
  • 242

2 Answers2

9

You should add -lm to your compiler option.

Besides of that, you could also change -lpthread to -pthread.

rralf
  • 1,202
  • 15
  • 27
  • As to why it's required, see [this](http://stackoverflow.com/a/4606406/1919302) :) – amrith92 Apr 04 '13 at 11:50
  • Just to give this some additional info: With "-lm" your linking against the math library (in words: "-link math"). Include math.h is not enough in this case. – puelo Apr 04 '13 at 11:51
  • For completeness, you should add "-lm" to your call to gcc but *at the end of the command*, or at least at the right side of your compilation unit. That's becuse the linker expects to find objects and libraries in dependency order: first (left) the user (your compilation unit) and later (right) the provider (the library). For example, try to move your "lpthread" to the left end of your call to gcc and you'll find that gcc will not be able to resolve your POSIX threads calls. Best regards, /Ángel – Angel Oct 30 '16 at 07:10
2

In the end, it has to be like this: gcc -pedantic -Wall -o theaded_program pth.c -pthread -lm

ahmacleod
  • 4,280
  • 19
  • 43
DevBush
  • 383
  • 1
  • 3
  • 10