QtCreator中CMake调用pkg-config失败编译报错求助
Hey there, let's get this sorted out! The issue you're facing is because CMake doesn't interpret shell-style backticks the way a terminal does—when you put pkg-config --cflags --libs gtk+-3.0 directly into CMAKE_CXX_FLAGS, it's passing those exact strings as compiler arguments instead of running the pkg-config command to get the actual flags. Here's how to fix it properly:
The Right Way: Use CMake's PkgConfig Module
CMake has a built-in module to handle pkg-config seamlessly, which is the recommended approach for cross-platform compatibility. Replace your existing CMAKE_CXX_FLAGS line with these steps in your CMakeLists.txt:
Find the pkg-config tool (make sure it's installed on your system first):
find_package(PkgConfig REQUIRED)Locate GTK+3 libraries and headers using pkg-config:
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)Add GTK+3's include directories to your project:
include_directories(${GTK3_INCLUDE_DIRS})Add GTK+3's library directories:
link_directories(${GTK3_LIBRARY_DIRS})Apply additional compiler flags from GTK+3:
add_definitions(${GTK3_CFLAGS_OTHER})Link your target against GTK+3 libraries:
# Replace "your_project_name" with the actual name of your executable/target target_link_libraries(your_project_name ${GTK3_LIBRARIES})
Why This Works
The pkg_check_modules command runs pkg-config behind the scenes, parses its output, and stores the necessary flags in variables like ${GTK3_INCLUDE_DIRS} and ${GTK3_LIBRARIES}. CMake then uses these variables correctly to configure your compiler and linker settings.
Pre-Requisites to Double-Check
Make sure you have the required packages installed on your system:
- On Debian/Ubuntu-based systems:
sudo apt-get install pkg-config libgtk-3-dev - On Fedora/RHEL:
sudo dnf install pkg-config gtk3-devel
Alternative: Manual pkg-config Execution (Not Recommended)
If you really want to run pkg-config manually (though the module approach is better), you can use CMake's execute_process to capture the output:
execute_process( COMMAND pkg-config --cflags gtk+-3.0 OUTPUT_VARIABLE GTK_CFLAGS OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND pkg-config --libs gtk+-3.0 OUTPUT_VARIABLE GTK_LIBS OUTPUT_STRIP_TRAILING_WHITESPACE ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 ${GTK_CFLAGS}") target_link_libraries(your_project_name ${GTK_LIBS})
After updating your CMakeLists.txt, go back to Qt Creator, re-run CMake configuration (via "Projects" tab > "Build" > "Run CMake"), and try compiling again—it should work now!
内容的提问来源于stack exchange,提问作者user9074174

