Search code examples
macoscmakeshared-libraries

How to link a shared library using CMake, MacOS


I built a shared library called foo_shared_debug.dylib. I want to link it to an executable I have called bar.

I was able to built bar, but during runtime I got a

dyld[xxxx]: Library not loaded: foo_shared_debug.dylib ...

Here is my directory structure

  • shared
    • foo.h
    • foo_shared_debug.dylib
  • CMakeLists.txt
  • main.cpp

Here is my CMakeLists.txt

cmake_minimum_required(VERSION 3.28)
project(tryshared)

set(CMAKE_CXX_STANDARD 23)

add_library(foo SHARED IMPORTED GLOBAL)
set_target_properties(foo PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/shared/foo_shared_debug.dylib)
add_executable(bar main.cpp)
target_link_libraries(bar foo)

I am able to resolve the issue if I also put the foo_shared_debug.dylib in /usr/local/lib, but that is not ideal. Any ideas? Thanks.


Solution

  • I end up putting the library (foo_shared_debug.dylib) directly in the build folder (${CMAKE_BINARY_DIR}). Then my CMakeLists.txt file becomes:

    add_library(foo SHARED IMPORTED GLOBAL)
    set_target_properties(foo PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/foo_shared_debug.dylib)
    add_executable(bar main.cpp)
    target_link_libraries(bar foo)