nbilal
nbilal

Reputation: 1099

Where is libdl.so on Mac OS X?

I am very new to Mac and trying to compile some code that links to libdl.so.

I use CMake to configure my project and in my CMakeList I have:

IF(UNIX)
        FIND_LIBRARY(LIBDL_LIB NAMES libdl.so
                        PATHS /usr/lib/ usr/lib64/)
        TARGET_LINK_LIBRARIES(PLUGINS_FRAMEWORK ${LIBDL_LIB})
ENDIF(UNIX)

This works fine on Ubuntu however libdl.so is not there on Mac OS X 10.9.

Where is libdl.so on Mac OS X ?

If it's not there how do I get it ?

Thanks !

Upvotes: 2

Views: 3855

Answers (2)

VestniK
VestniK

Reputation: 1920

There is platform independent way to add linker flags necessry to use dlopen. Cmake provides variable CMAKE_DL_LIBS:

The name of the library that has dlopen and dlclose in it, usually -ldl on most UNIX machines.

One can use it instead of manual search for -ldl and taking platform differences into account:

target_link_libraries(PLUGINS_FRAMEWORK PUBLIC ${CMAKE_DL_LIBS}) 

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

You don't need a special library to get dlopen() etc on Mac OS X. And shared objects end in .dylib or .bundle on Mac OS X.

This code compiles with no extra libraries:

#include <dlfcn.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    char *name = "libc.dylib";
    if (argc > 1)
        name = argv[1];
    void *dlh = dlopen(name, 0);
    if (dlh == 0)
        printf("Failed to dlopen() %s\n", name);
    else
        printf("Got handle %p from dlopen() for %s\n", dlh, name);
    dlclose(dlh);
    return 0;
}

It runs and produces:

Got handle 0x7fff624e9378 from dlopen() for libc.dylib

Compilation:

gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Werror dl.c -o dl

I'm using GCC 4.8.2 on Mac OS X 10.9 Mavericks, but the answer would be the same on any version of Mac OS X that's still in support.


Be aware that the equivalent of ldd on Mac OS X is otool -L, and it produces:

$ otool -L dl
dl:
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
    /usr/gcc/v4.8.2/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
$

I'm not sure what behind-the-scenes magic or skulduggery means that opening libc.dylib actually works. However:

$ ./dl libSystem.B.dylib
Got handle 0x7fff6e398378 from dlopen() for libSystem.B.dylib
$ ./dl
Got handle 0x7fff690d2378 from dlopen() for libc.dylib
$

The address is the same for both, so there's probably some mapping going on behind the scenes.

Upvotes: 2

Related Questions