llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
27.92k stars 11.53k forks source link

Cannot link to libLLVM due to command line parser static initialization #60888

Open rickmark opened 1 year ago

rickmark commented 1 year ago

The exported libLLVM.dylib cannot be used as is because it creates multiple static initializers for cl::opt<T> values that may interfere with a command line application that links to the library. I suspect that the macOS linker may have liked multiple objects that have the static initializer, leading the the requisite error. Fixes may include allowing duplicate identical initializers to exist without error, or to create libLLVM by first passing through all object files to llvm-link before generating the native binary as this would fix any single instance problems with static initialization. I believe that lld may properly handle these duplicate object files, but will know more after a few tests. Error as reported:

: CommandLine Error: Option 'aarch64-enable-ccmp' registered more than once!
LLVM ERROR: inconsistency in registered CommandLine options

Repo steps:

Create libLLVM by compiling LLVM with LLVM_BUILD_LLVM_DYLIB=ON and then create a binary that links to LLVM using something similar to the following CMake file:

cmake_minimum_required(VERSION 3.24)
project(bug_sample)

set(CMAKE_CXX_STANDARD 20)
set(LLVM_ROOT /opt/latest-apple-llvm)
set(LLVM_INCLUDE_DIR ${LLVM_ROOT}/include)
set(LLVM_LIB_DIR ${LLVM_ROOT}/lib)

find_package(Boost 1.80 REQUIRED COMPONENTS filesystem program_options)
link_directories(${LLVM_LIB_DIR})
include_directories(${LLVM_INCLUDE_DIR} ${Boost_INCLUDE_DIRS})
add_executable(bug_sample main.cpp)
target_link_libraries(bug_sample LLVM clang clang-cpp Boost::filesystem Boost::program_options)
rickmark commented 1 year ago

Ah doh, this defect pretty much occurs when you are linking to both libLLVM and libClang.