gpt4 book ai didi

linker - 在 MacOSX 上静态链接时找不到符号

转载 作者:行者123 更新时间:2023-12-01 01:51:18 25 4
gpt4 key购买 nike

我正在尝试创建一个静态库并将其链接到 MacOS X(几个版本)上:
文件 foo.c :

char foo[111];

文件 bar.c :
#include <string.h>

extern char foo[];

int bar(char *src) {
strcpy(foo, src);
return strlen(foo);
}

创建一个库:
$ cc -c foo.c bar.c
$ ar r libfoobar.a foo.o bar.o
ar: creating archive libfoobar.a
$ ranlib libfoobar.a
$ nm libfoobar.a

libfoobar.a(foo.o):
000000000000006f C _foo

libfoobar.a(bar.o):
U ___strcpy_chk
0000000000000000 T _bar
U _foo
U _strlen

创建一个小测试程序:

文件 main.c :
#include <stdio.h>

int bar(char *);

int main(void) {
printf("foobarbar = %i\n", bar("123"));
return 0;
}

编译并链接:
$ cc -c main.c
$ cc -o m main.o -L. -lfoobar
Undefined symbols for architecture x86_64:
"_foo", referenced from:
_bar in libfoobar.a(bar.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

为什么找不到符号?它在 foo.c 中定义?至少不应该 ranlib在库中创建一个索引,允许文件的随机顺序?

相同的代码在 Linux (gcc) 下运行良好,当 foo.c 中的符号时也是如此。不是char数组,而是int。

最佳答案

还有一个类似的问题:Object files not properly added to archive on mac其中有 this answer :

Option 1:

ar -rs my_archive.a foo.o bar.o other_object_files.o
ranlib -c my_archive.a

Option 2:

libtool -c -static -o my_archive.a foo.o bar.o other_object_files.o

-cranlib 上的两个选项都有影响的标志和 libtool分别:

-c

Include common symbols as definitions with respect to the table of contents. This is seldom the intended behavior for linking from a library, as it forces the linking of a library member just because it uses an uninitialized global that is undefined at that point in the linking. This option is included only because this was the original behavior of ranlib. This option is not the default.

关于linker - 在 MacOSX 上静态链接时找不到符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com