代码之家  ›  专栏  ›  技术社区  ›  telliott99

初学者的问题,试图理解链接器如何搜索静态库

  •  1
  • telliott99  · 技术社区  · 15 年前

    我有一个工作设置,所有文件都在同一个目录(桌面)中。终端输出如下所示:

    $ 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
    

    文件:

    mymath.c:

    float mysqrt(float n) {
      return 10.2;
    }
    

    测试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;
    }
    

    现在,我将归档文件mymath.a移动到子目录/temp中。我无法使链接正常工作:

    $ 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
    

    更新:谢谢你的帮助。所有答案基本正确。我在博客上写了这件事 here .

    3 回复  |  直到 15 年前
        1
  •  1
  •   Ramashalanka    15 年前

    要包含数学库,请使用-lm,而不是-lmath。此外,在链接时,还需要对子目录使用-L来包含库(-I只包含用于编译的头)。

    您可以编译并链接到:

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

    或与

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

    看见 link text 有关使用-l的实践的评论(搜索“糟糕的编程”):

        2
  •  2
  •   indiv Olivier Poulin    15 年前
    $ gcc test.c /Users/telliott_admin/Desktop/temp/mymath.a -o test
    

        3
  •  1
  •   bmargulies    15 年前

    为了让ld找到带有-l的库,必须根据模式库对其进行命名 A.然后使用-lmymath

    所以,没有办法将/temp/mymath.a与-l结合起来。

    如果您将其命名为libmymath.a,那么-L/temp-lmymath就会找到它。