简体   繁体   中英

Static Library Linking Issue "Undefined symbols" for symbols that are defined

I am using Apple LLVM version 8.0.0 (clang-800.0.42.1) to compile. It's about 1200 files, but I have used them before. I go and compile them all, no problems. Then I make my static library ( ar rcs libblib.a *.o ), no problems. So when I try to use my brand new library, I have my problem.

gcc main.c  -L. -lblib
Undefined symbols for architecture x86_64:
  "_N_method", referenced from:
      _main in main-7fc584.o
ld: symbol(s) not found for architecture x86_64

But, I know this is defined. I check to see that the file is included ( ar -t libblib.a | grep N_METHOD.o ) and it is in there. Check the source file, and there is the method, exactly named as it is in the header file. What is the problem I am having here? I am at a complete loss and I am hoping I am missing something simple.

I did nm -g N_METHOD.o and got back:

0000000000000000 T __Z8N_methodP6stacks

Transferring comments into an answer.

Based on the question content, I asked:

  • Have you checked that N_METHOD.o is a 64-bit object file (or a fat object file with both 32-bit and 64-bit code in it)? If it is a 32-bit object file, then it is no use for a 64-bit program. However, that's a little unlikely; you have to go out of your way to create a 32-bit object file on Mac.

  • Have you run nm -g N_METHOD.o to see whether _N_method is defined in the object file?

I did nm -g N_METHOD.o and got back:

 0000000000000000 T __Z8N_methodP6stacks

Don't compile C code with a C++ compiler. Or don't try to compile C++ code with a C compiler. The mangled name ( __Z8N_methodP6stacks ) is for C++. Maybe you simply need to link with g++ instead of gcc ? They are different languages — this is the property of 'type-safe linkage' that is characteristic of C++ and completely unknown to C.

First step — compile and link with:

g++ main.c -L. -lblib

Assuming that the source is in the C++ subset of C (or C subset of C++), then the chances are that should work. At least, if the code contains N_Method(&xyz) where xyz is a variable of type stacks , then there's a chance it will call __Z8N_methodP6stacks .

The following code:

typedef struct stacks stacks;
extern int N_method(stacks*);

extern int relay(stacks *r);

int relay(stacks *r) { return N_method(r); }

compiles with a C++ compiler to produce the nm -g output:

0000000000000000 T __Z5relayP6stacks
                 U __Z8N_methodP6stacks

It also compiles with a C compiler to produce the nm -g output:

0000000000000038 s EH_frame1
                 U _N_method
0000000000000000 T _relay

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM