1

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

$ 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

我错过了什么?你会推荐什么资源?

更新:感谢您的帮助。所有的答案基本上都是正确的。我在这里写了博客。

4

3 回答 3

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

编辑:gcc 只需要静态库的完整路径。您使用 -L 给出 gcc 应该与 -l 一起搜索的路径。

于 2010-02-02T20:16:00.110 回答
1

要包含数学库,请使用 -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

其中 mymath.a 被重命名为 libmymath.a。

有关使用 -l 的做法的评论(搜索“糟糕的编程”),请参见链接文本:

于 2010-02-02T20:03:42.927 回答
1

为了让 ld 找到带有 -l 的库,它必须根据模式 lib yourname .a 命名。然后你使用 -lmymath

因此,没有办法让它使用 -l 来获取 /temp/mymath.a。

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

于 2010-02-02T20:17:16.973 回答