使用CMake编译MagickWand程序失败,求助解决方案
Fixing Undefined Reference Errors for MagickWand and pthread in CMake
Let's break down your errors and fix them step by step:
1. Understanding the Root Issues
pthread_createundefined reference: Your code uses C++11'sstd::thread, which requires explicit linking against the POSIX threads library (pthread).- MagickWand function undefined references: You weren't properly linking against the MagickWand library, and your include directory setup wasn't aligned with how CMake's ImageMagick package resolves header paths.
2. Corrected CMakeLists.txt
Replace your existing CMakeLists.txt with this version—each change is explained below:
cmake_minimum_required(VERSION 3.0) project(ScreenRecorder) # Set C++ standard, warnings, and add pthread support for std::thread set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pthread") # Define source and output directories set(source_dir "${PROJECT_SOURCE_DIR}/source/") set(EXECUTABLE_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/bin/") # Explicitly find ImageMagick with MagickWand component find_package(ImageMagick REQUIRED COMPONENTS MagickWand) # Use CMake-provided variables for includes and library paths include_directories(${ImageMagick_INCLUDE_DIRS}) link_directories(${ImageMagick_LIBRARY_DIRS}) # Gather all source files file(GLOB src_files "${source_dir}*.cpp") # Build executable and link against required libraries add_executable(ScreenRecorder ${src_files}) target_link_libraries(ScreenRecorder PRIVATE ${ImageMagick_LIBRARIES})
3. Key Changes Explained
- Thread Support: Added
-pthreadtoCMAKE_CXX_FLAGS—this handles both compilation flags and linking for the pthread library, fixing thepthread_createerror. - Targeted ImageMagick Lookup: Using
find_package(ImageMagick REQUIRED COMPONENTS MagickWand)tells CMake to specifically locate the MagickWand libraries and headers, which correctly populates variables like${ImageMagick_INCLUDE_DIRS}and${ImageMagick_LIBRARIES}. This resolves the "wand/MagickWand.h not found" issue you encountered earlier. - Proper Library Linking: Replaced your manual directory-only
link_librariescall withtarget_link_librariestied to the executable. This ensures the linker uses the exact MagickWand libraries identified by CMake, not just a generic directory. - Modern C++ Standard Setup: Switched to
CMAKE_CXX_STANDARDinstead of hardcoding-std=c++14—this is the recommended CMake way to set language standards and avoids potential conflicts.
4. Verify the Fix
Clean your existing build directory (if you have one) and re-run the build commands:
rm -rf build/ mkdir build && cd build cmake .. make
This should resolve both sets of undefined reference errors and successfully compile your program.
内容的提问来源于stack exchange,提问作者PrograMed IP
相关产品推荐
相关产品推荐

