在MacOSX上进行静态链接时找不到符号 [英] Symbol not found when static linking on MacOSX

查看:225
本文介绍了在MacOSX上进行静态链接时找不到符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a static library and link it on MacOS X (several versions): File 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

创建一个小型测试程序:

Create a small test program:

文件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不应在该库中创建一个允许该文件随机排列的索引吗?

Why is the symbol not found? It is defined in foo.c? Shouldn't at least ranlib create an index in the library that allows a random order of the files there?

相同的代码在Linux(gcc)下以及在foo.c中的符号不​​是char数组,而是int时也能很好地工作.

The same code works well under Linux (gcc), and also when the symbol in foo.c is not a char array, but an int.

推荐答案

还有一个类似的问题:这个答案:

There is a similar question: Object files not properly added to archive on mac which has 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

-c标志分别使ranliblibtool的两个选项有所不同:

It is -c flag that makes a difference for both options on ranlib and libtool respectively:

-c

包括常用符号作为关于表的定义 内容.这很少是链接的预期行为 从图书馆,因为它强制链接图书馆成员 只是因为它使用了未定义的未初始化的全局变量 在链接的那一点上.仅包含此选项 因为这是ranlib的原始行为.这个选项 不是默认值.

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.

这篇关于在MacOSX上进行静态链接时找不到符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆