将 qmake 转换为 CMake

Convert qmake into 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)

但我收到 "can not specify target link library for nanomsg which is not build by this project" 错误。我构建了与另一个项目对齐的库。

当我删除 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() 用于 link 一个库到 另一个 库(或可执行文件),因此语法应至少包含两个参数。例如,如果你想 link 静态 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)