cmake - 将 qmake 转换为 CMake
问题描述
我是 CMake 的新手,但我曾经使用过 qmake。在我的 qmake 中,我有以下内容用于在项目文件夹内的名为 bin 的文件夹中添加一个静态库:
QT -= gui
QT += core
CONFIG += c++11 console
CONFIG -= app_bundle
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp
macx: LIBS += -L$$PWD/bin/lib/ -lnanomsg
INCLUDEPATH += $$PWD/bin/include
DEPENDPATH += $$PWD/bin/include
macx: PRE_TARGETDEPS += $$PWD/bin/lib/libnanomsg.a
对应的 CMake 语法是什么?
我尝试了以下方法:
INCLUDE_DIRECTORIES(./bin/include)
LINK_DIRECTORIES($(CMAKE_SOURCE_DIR)/bin/lib/)
TARGET_LINK_LIBRARIES(nanomsg)
但我得到“无法为不是由该项目构建的 nanomsg 指定目标链接库”错误。我构建了与另一个项目对齐的库。
当我删除 时target_link_libraries
,我得到未定义符号的链接器错误。
[更新:这是最终的工作 CMake 文件]
cmake_minimum_required(VERSION 3.0.0)
project(cmake-linkstatic VERSION 0.1 LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
find_package(Qt5Core)
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries(${PROJECT_NAME} Qt5::Core)
#this line is not needed any more
#INCLUDE_DIRECTORIES(${CMAKE_CURRENT_LIST_DIR}/bin/include)
add_library(nanomsg STATIC IMPORTED)
# Specify the nanomsg library's location and include directories.
set_target_properties(nanomsg PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_LIST_DIR}/bin/lib/libnanomsg.a"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/bin/include"
)
# Define your executable CMake target.
# Link the nanomsg library to the executable target.
target_link_libraries(${PROJECT_NAME} nanomsg)
解决方案
如果要在 CMake 中使用预构建的静态库,可以声明STATIC IMPORTED
CMake 目标:
add_library(nanomsg STATIC IMPORTED)
# Specify the nanomsg library's location and its include directories.
set_target_properties(nanomsg PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_LIST_DIR}/bin/lib/libnanomsg.a"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/bin/include"
)
在这里,我们使用CMAKE_CURRENT_LIST_DIR
变量来访问当前 CMakeLists.txt 文件所在的目录。
target_link_libraries()
用于将一个库链接到另一个库(或可执行文件),因此语法应至少包含两个参数。例如,如果您想将静态nanomsg
库链接到可执行文件(例如MyExecutable
),您可以在 CMake 中这样做:
add_library(nanomsg STATIC IMPORTED)
# Specify the nanomsg library's location and include directories.
set_target_properties(nanomsg PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_LIST_DIR}/bin/lib/libnanomsg.a"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/bin/include"
)
# Define your executable CMake target.
add_executable(MyExecutable main.cpp)
# Link the nanomsg library to the executable target.
target_link_libraries(MyExecutable PUBLIC nanomsg)
推荐阅读
- mysql - 使用 if 语句创建触发器时 MySql 错误 1064
- excel - Workbook_Open() 不适用于工作簿保护
- php - 如何首先验证多个文件,然后仅在它们有效时才将其余的表单数据添加到数据库中?
- javascript - 如何阻止加载强制在我的网站管理面板上显示广告的外部脚本
- javascript - 如何正确居中项目(固定宽度 - 滑动滑动)?
- java - 显示我订购的所有商品
- spring-boot - 在 spring boot 2.3.3 中,面临有关 CORS 的问题。没有使用弹簧安全
- vue.js - Nuxtjs 组件不会在 v-if 条件更改时重新加载
- reactjs - Line7:1:解析错误:“import”和“export”可能只出现在顶层
- javascript - useState 不适用于 React 应用程序中的渲染