Link mimalloc with --as-needed on Linux (#8211)
The mimalloc CMake code unconditionally adds libatomic to its link
dependencies, but it's not actually needed on the modern systems
that we're building for. Adding the --as-needed flag causes the
linker to only link against the following libraries if they
provide symbols that are actually needed.
For static linking, we wrap mimalloc's injected dependencies in
-Wl,--as-needed since they surface all the way up to the final
link line for each tool (I don't think it would hurt to just
link all the tools with --as-needed but this seemed cleaner).
For dynamic linking, it's sufficient to just make the libmimalloc.so
link with --as-needed.
As a drive-by cleanup, also make mimalloc a private dependency of
libbinaryen.
Fixes https://github.com/emscripten-core/emsdk/issues/928
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6b4cf08..1f1d97a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -478,9 +478,10 @@
add_link_flag("-Bsymbolic")
endif()
endif()
-target_link_libraries(binaryen Threads::Threads)
+target_link_libraries(binaryen PUBLIC Threads::Threads)
+binaryen_setup_rpath(binaryen)
if(BUILD_LLVM_DWARF)
- target_link_libraries(binaryen llvm_dwarf)
+ target_link_libraries(binaryen PRIVATE llvm_dwarf)
endif()
if(BUILD_MIMALLOC)
@@ -489,9 +490,12 @@
endif()
message(STATUS "Building with mimalloc allocator.")
if(BUILD_STATIC_LIB)
- target_link_libraries(binaryen mimalloc-static)
+ target_link_libraries(binaryen PRIVATE "-Wl,--push-state,--as-needed")
+ target_link_libraries(binaryen PRIVATE mimalloc-static)
+ target_link_libraries(binaryen PRIVATE "-Wl,--pop-state")
else()
- target_link_libraries(binaryen mimalloc)
+ target_link_options(mimalloc PRIVATE "-Wl,--as-needed")
+ target_link_libraries(binaryen PRIVATE mimalloc)
endif()
endif()