views:

51

answers:

3

I have a working setup, where all files are in the same directory (Desktop). The Terminal output is like so:

$ gcc -c mymath.c
$ ar r mymath.a mymath.o
ar: creating archive mymath.a
$ ranlib mymath.a
$ gcc test.c mymath.a -o test
$ ./test
Hello World!
3.14
1.77
10.20

The files:

mymath.c:

float mysqrt(float n) {
  return 10.2;
}

test.c:

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

main() {
  printf("Hello World!\n");
  float x = sqrt(M_PI);
  printf("%3.2f\n", M_PI);
  printf("%3.2f\n", sqrt(M_PI));
  printf("%3.2f\n", mysqrt(M_PI));
  return 0;
}

Now, I move the archive mymath.a into a subdirectory /temp. I haven't been able to get the linking to work:

$ gcc test.c mymath.a -o test -l/Users/telliott_admin/Desktop/temp/mymath.a
i686-apple-darwin10-gcc-4.2.1: mymath.a: No such file or directory

$ gcc test.c -o test -I/Users/telliott_admin/Desktop/temp -lmymath
ld: library not found for -lmymath
collect2: ld returned 1 exit status

What am I missing? What resources would you recommend?

Update: Thanks for your help. All answers were basically correct. I blogged about it here.

+1  A: 

To include the math libraries, use -lm, not -lmath. Also, you need to use -L with the subdirectory to include the library when linking (-I just includes the header for compiling).

You can compile and link with:

gcc test.c -o test -I/Users/telliott_admin/Desktop/temp /Users/telliott_admin/Desktop/temp/mymath.a

or with

gcc test.c -o test -I/Users/telliott_admin/Desktop/temp -L/Users/telliott_admin/Desktop/temp -lmymath

where mymath.a is renamed libmymath.a.

See link text for comments (search for "bad programming") on the practices of using -l:

Ramashalanka
Sorry for the typo. I'm looking for my own "fake" library: mymath which is in /temp
telliott99
Yep. These both worked for me. Thanks.
telliott99
+2  A: 
$ gcc test.c /Users/telliott_admin/Desktop/temp/mymath.a -o test

edit: gcc only needs the full path to the library for static libraries. You use -L to give a path where gcc should search in conjunction with -l.

indiv
+1  A: 

In order for ld to find a library with -l, it must be named according to the pattern libyourname.a. Then you use -lmymath

So, there is no way to get it to take /temp/mymath.a with -l.

If you named it libmymath.a, then -L/temp -lmymath would find it.

bmargulies