首页 > 解决方案 > 将 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)

标签: cmakelinkerstatic-librariesqmake

解决方案


如果要在 CMake 中使用预构建的静态库,可以声明STATIC IMPORTEDCMake 目标:

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)

推荐阅读