在LLVM源码外构建Pass时遭遇未定义符号错误求助
Hey there! Let's work through this undefined symbol issue you're hitting with your out-of-tree LLVM Pass. I remember struggling with similar problems when I first started building passes outside the LLVM source tree, so here's a breakdown of what's going wrong and how to fix it:
What's Causing the Error?
The undefined symbol error (_ZNK4llvm10ModulePass17createPrinterPassERNS_11raw_ostreamERKSs) means your TestPass.so module isn't properly linking against the LLVM libraries that provide the ModulePass base class implementation. Even though you set up the main CMakeLists.txt to find LLVM, your subdirectory build isn't actually linking against the necessary LLVM components.
Step-by-Step Fix
Let's adjust your CMake configurations to ensure proper linking:
Update the Main CMakeLists.txt
Add a line to map the LLVM components your pass uses to their corresponding libraries. Most basic passes need at least theCorecomponent (for core IR functionality), plus others likeAnalysisorTransformUtilsdepending on your pass logic:cmake_minimum_required(VERSION 3.4.3) project(SimpleProject) find_package(LLVM REQUIRED CONFIG) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -fno-rtti -D_GLIBCXX_USE_CXX11_ABI=0") include_directories(${LLVM_INCLUDE_DIRS}) add_definitions(${LLVM_DEFINITIONS}) # Map required LLVM components to libraries llvm_map_components_to_libs(LLVM_LIBS Core Analysis TransformUtils) add_subdirectory(testpass)Link Libraries in the Subdirectory CMakeLists.txt
Modify your testpass directory's CMake config to link against the LLVM libraries we just defined:add_library(TestPass MODULE TestPass.cpp) # Link the required LLVM libraries to your pass module target_link_libraries(TestPass PRIVATE ${LLVM_LIBS})
Additional Checks to Avoid Future Issues
- Match LLVM Versions: Make sure the
optyou're running is from the exact same LLVM version you used to compile your pass. Version mismatches will almost always cause symbol or ABI errors. - Verify ABI Consistency: The
-D_GLIBCXX_USE_CXX11_ABI=0flag in your CXX_FLAGS must match the ABI setting LLVM was compiled with. If LLVM was built with the C++11 ABI enabled, this flag will cause conflicts—double-check your LLVM build config if you're unsure. - Check Pass Implementation: Ensure your
TestPassclass correctly inherits fromllvm::ModulePassand implements all required methods (likerunOnModule). While the missing symbol is a linking issue, incorrect inheritance can sometimes lead to similar-looking errors.
Final Run Command
After rebuilding your pass, make sure to use the correct opt binary (from your LLVM installation) when loading the module:
/path/to/your/llvm/bin/opt -load /path/to/testpass/TestPass.so -TestPass < testprogram.bc > /dev/null
(Note: I added a dash before TestPass in the command—LLVM pass names need to be prefixed with a dash when invoking them.)
内容的提问来源于stack exchange,提问作者DuckOfDoom

