我一直在使用Clion IDE,并试图获取一个简单的GTK程序来使用它进行编译。我发现Clion使用CMake,所以问题出在这里,而不是IDE本身。我能够直接从终端成功编译并运行该程序,但使用CMake失败。
这个问题很简单:当我尝试编译,编译器找不到gtk.h,它位于/usr/include/gtk-3.0/gtk/gtk.h
。我发现命令编译器参数以某种方式'pkg-config --libs --cflags gtk+-3.0'
解决了此问题,但是我无法使用CMake添加此参数。
我试过了:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} `pkg-config --libs --cflags gtk+-3.0`")
但是遇到了:
Linking CXX executable test
c++: error: `pkg-config: No such file or directory
c++: error: gtk+-3.0`: No such file or directory
c++: error: unrecognized command line option ‘--libs’
c++: error: unrecognized command line option ‘--cflags’
make[3]: *** [test] Error 1
make[2]: *** [CMakeFiles/test.dir/all] Error 2
make[1]: *** [CMakeFiles/test.dir/rule] Error 2
make: *** [test] Error 2
有什么建议?
进一步的研究发现本教程正是针对我所遇到的问题。它的工作原理很像魅力,但似乎将许多看似未定义的变量加入了混合。谁能解释这是如何以及为什么起作用的?
# Set the name and the supported language of the project
project(hello-world C)
# Set the minimum version of cmake required to build this project
cmake_minimum_required(VERSION 2.6)
# Use the package PkgConfig to detect GTK+ headers/library files
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
# Setup CMake to use GTK+, tell the compiler where to look for headers
# and to the linker where to look for libraries
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
# Add other flags to the compiler
add_definitions(${GTK3_CFLAGS_OTHER})
# Add an executable compiled from hello.c
add_executable(hello main.c)
# Link the target to the GTK+ libraries
target_link_libraries(hello ${GTK3_LIBRARIES})
使用FindPkgConfig模块
cmake_minimum_required(VERSION <your cmake version>)
project(myproject CXX)
# Find the GTK module using pkg-config
include(FindPkgConfig)
pkg_check_modules(GTK REQUIRED "gtk+-3.0")
# Add the path to its header files to the compiler command line
include_directories(${GTK_INCLUDE_DIRS})
# Add any compiler flags it requires
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GTK_CFLAGS} <other flags>")
# Add the makefile target for your executable and link in the GTK library
add_executable(${CMAKE_PROJECT_NAME} <list of source files>)
target_link_libraries(${CMAKE_PROJECT_NAME} ${GTK_LDFLAGS} <other libraries>)
人字形(<...>
)中的位需要替换为实数值
你可以找到更多
cmake --help-module FindPkgConfig
基本上,该include(FindPkgConfig)
行引入了一些宏-它还确保pkg-config在环境中可用。然后,调用将pkg_check_modules
有效运行pkg-config
,解析输出并使用第一个参数作为词干创建一组变量。
在帮助中,这是一个基本列表(XPREFIX通常是您提供的词干)
<XPREFIX>_FOUND ... set to 1 if module(s) exist
<XPREFIX>_LIBRARIES ... only the libraries (w/o the '-l')
<XPREFIX>_LIBRARY_DIRS ... the paths of the libraries (w/o the '-L')
<XPREFIX>_LDFLAGS ... all required linker flags
<XPREFIX>_LDFLAGS_OTHER ... all other linker flags
<XPREFIX>_INCLUDE_DIRS ... the '-I' preprocessor flags (w/o the '-I')
<XPREFIX>_CFLAGS ... all required cflags
<XPREFIX>_CFLAGS_OTHER ... the other compiler flags
<XPREFIX> = <PREFIX> for common case
<XPREFIX> = <PREFIX>_STATIC for static linking
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句