CMake:如何链接静态第三方库?

时间:2011-08-14 20:32:07

标签: build linker build-process cmake

我拥有的内容:我的代码(简单的main.cpp),第三方库(EnvVar TPLIB_INCLUDE)的标题,二进制库(TPLIB_BINARY_PATH中的几个.a文件)和以下CMakeLists。 TXT:

# current source directory: CMAKE_CURRENT_SOURCE_DIR
# current binary directory: CMAKE_CURRENT_BINARY_DIR

# require 2.6 to get support for the simple IF construct
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)

PROJECT( simpleapp)
SET( PROGNAME simpleapp )

SET( CMAKE_COLOR_MAKEFILE ON )
SET( CMAKE_VERBOSE_MAKEFILE ON )
SET( CMAKE_INCLUDE_CURRENT_DIR TRUE )

# the actual .cpp files go here
SET(project_SOURCES
    main.cpp
)

# add here all files that need processing by Qt's MOC if there are any
set(project_MOC_SOURCES
    # files would go here
)

# add here all files that will be processed by Qt's UIC
set(project_UIS
    # all .ui files would go here
)

# additional Qt resources go here
set(project_RCCS
    # all .qrc files would go here
)

# setup Qt
FIND_PACKAGE(Qt4 REQUIRED)

INCLUDE(${QT_USE_FILE})

QT4_WRAP_CPP(test_MOCS ${project_MOC_SOURCES})
QT4_WRAP_UI(test_UIS_H ${project_UIS})
QT4_WRAP_CPP(test_MOC_UI ${project_UIS_H})
QT4_ADD_RESOURCES(test_RCC_SRCS ${project_RCCS})

include_directories( ${CMAKE_BINARY_DIR} $ENV{TPLIB_INCLUDE})

ADD_EXECUTABLE( ${PROGNAME} ${project_SOURCES} ${test_MOCS} ${test_RCC_SRCS} ${test_MOC_UI} )

link_directories($ENV{TPLIB_BINARY_PATH})

TARGET_LINK_LIBRARIES(${PROGNAME} ${QT_LIBRARIES} lib_misc lib_tools)

make创建main.cpp.o的项目照常工作。因此,CMake找到了第三方标题。说到链接ld,抱怨无法找到-llib_misc和-llib_tools。 删除“link_directories”行或指定libs绝对名称会导致“没有规则来制作目标/path/to/lib_misc.a”

那么如何告诉CMake只使用这些库进行链接?

1 个答案:

答案 0 :(得分:9)

link_directories($ENV{TPLIB_BINARY_PATH})应放在ADD_EXECUTABLE之前。

来自the official documents of CMakelink_directories上有注释:

  

该命令仅适用于调用后创建的目标。