Symbol not found when statically linked to MacOSX

I am trying to create a static library and link it with MacOS X (multiple versions): File foo.c

:

char foo[111];

      

File bar.c

:

#include <string.h>

extern char foo[];

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

      

Create library:

$ 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:

File main.c

:

#include <stdio.h>

int bar(char *);

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

      

Compile and link:

$ 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)

      

Why was the symbol not found? foo.c

Is it defined in ? Shouldn't at least ranlib

create an index in the library that allows random order of files there?

The same code works well on Linux (gcc) and also when the character in is foo.c

not a char array but an int.

+2


source to share


1 answer


There is a similar question: Object files that have not been 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

      



This is the flag -c

that makes the difference for both options on ranlib

and libtool

respectively:

-c

Include common symbols as definitions for the table of contents. This is rarely related to the intended behavior for linking from a library, as it forces linking to a library item simply because it uses an uninitialized global which is undefined at that point in the link. This option is only included because this was the original behavior of ranlib. This parameter is not the default.

+1


source







All Articles