How to compile shared lib with clang on osx

28,273

By using:

-Wl,-undefined -Wl,dynamic_lookup

or

clang -shared -undefined dynamic_lookup -o libfoo.so foo.c

seems to maintain the same behaviour of GCC.

Share:
28,273
giskard
Author by

giskard

Updated on February 21, 2020

Comments

  • giskard
    giskard about 4 years

    source file

    rsetti::fastidio { /tmp }-> cat foo.c
    
        #include <stdio.h>
        void ACFunction() {
          printf("ACFunction()\n");
          AGoFunction();
        }
    

    compilation of shared lib

    rsetti::fastidio { /tmp }-> clang -shared -o libfoo.so foo.c
    
        foo.c:4:3: warning: implicit declaration of function 'AGoFunction' is invalid in C99 [-Wimplicit-function-declaration]
          AGoFunction();
          ^
        1 warning generated.
        Undefined symbols for architecture x86_64:
          "_AGoFunction", referenced from:
              _ACFunction in foo-lFDQ4g.o
        ld: symbol(s) not found for architecture x86_64
        clang: error: linker command failed with exit code 1 (use -v to see invocation)
    
    rsetti::fastidio { /tmp }->
    

    the same code on linux + gcc can be easily compiled.

  • oorst
    oorst over 7 years
    That did the trick. I knew it must have been something simple. Onwards!
  • rgov
    rgov over 5 years
    .dylib is the canonical extension for a shared library on macOS, using -dynamiclib instead of -shared. See stackoverflow.com/questions/2339679/…
  • ezolotko
    ezolotko over 4 years
    Please note that "-undefined dynamic_lookup" has unwanted side effects, like silencing the compiler diagnostics when you have some undefined symbols in your classes. These undefined symbols will then pop up later when trying to load your library at runtime with misleading errors, like "dlopen: image not found". See stackoverflow.com/a/30934307/71689 for details.