简体   繁体   中英

Create a simple dynamic library

What linking step am I missing? I'm trying to make a dynamic library from file cc :

#include "a.h"
#include "b.h"

int my_function(void)
{
  return a() + EIGHT;
}

which depends on ac :

int a(void)
{
  return 1;
}

and bh :

enum {
  EIGHT = 8,
};

I run gcc -c cc -o co to compile the object file. Then I run

gcc -Wall -dynamiclib -o libc.dylib c.c

and I get this error.

Undefined symbols for architecture x86_64:
  "_a", referenced from:
      _b in ccx5LSkL.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status 

How can I properly link the files? References addressing this specific problem would be awesome.

So your first line, gcc -c cc -o co , compiled the object file co . Now you then have to use co for creating the final result. So your linking step should be using co , not cc .

Next, the error you are getting is that the symbol "_a" was not found. This is coming from you calling the function a() , but not including it in the linking step. To do that you need to also compile ac and include it when linking your final product.

So in total, your process should be:

1) compile:

gcc -c a.c -o a.o
gcc -c c.c -o c.o

2) link:

gcc -Wall -dynamiclib -o libc.dylib a.o c.o

Note that to compile libc.dylib , you had to include all the sources that the final result would depend on.

Finally, you don't actually need to compile all of the object files separately. You can compile and link together in one combined step by just providing the *.c files right away.

gcc -Wall -dynamiclib -o libc.dylib a.c c.c

So your problem was really just about not including both sources together. (Other than -dynamiclib , everything actually works basically just like compiling a regular executable.)

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