无法在cmake中将库与测试二进制文件链接

时间:2016-06-17 18:07:33

标签: c++ c build msbuild cmake

我无法弄清楚如何使用Windows上的cmake将我的静态库与我的测试二进制文件链接起来。我做错了什么?

项目结构如下

MyProject
  - build
  - include
    - catch
      - *.h
    - MyProject
      - *.h
  - src
    - *.c
  - test
    - *.cpp
  - CMakeLists.txt

和CMakeLists.txt

CMAKE_MINIMUM_REQUIRED ( VERSION 3.3.1 )

SET ( NAME_LIB     "myproject" )
SET ( NAME_TEST    "test_myproject" )
SET ( PATH_BUILD   "${PROJECT_SOURCE_DIR}/build" )
SET ( PATH_INCLUDE "${PROJECT_SOURCE_DIR}/include" )
SET ( PATH_SOURCE  "${PROJECT_SOURCE_DIR}/src" )
SET ( PATH_TEST    "${PROJECT_SOURCE_DIR}/test" )

FILE ( GLOB SOURCES_LIB  "${PATH_SOURCE}/*.c" "${PATH_SOURCE}/*.cpp" )
FILE ( GLOB SOURCES_TEST "${PATH_TEST}/*.c" "${PATH_TEST}/*.cpp" )

INCLUDE_DIRECTORIES ("${PATH_INCLUDE}")

ADD_LIBRARY( ${NAME_LIB} STATIC "${SOURCES_LIB}" )
ADD_EXECUTABLE ( ${NAME_TEST} "${SOURCES_TEST}" )
TARGET_LINK_LIBRARIES ( ${NAME_TEST} "${PATH_BUILD}/${NAME_LIB}" )

使用cmake创建visual studio项目是可以的,但是当我尝试使用msbuild构建解决方案时,我收到以下错误。

(Link target) ->
  LINK : fatal error LNK1104: cannot open file 'myproject.obj' [D:\Source\myproject\build\test_myproject.vcxproj]

指定库名而不是绝对路径时出错。

test_myproject.obj : error LNK2019: unresolved external symbol "int __cdecl myproject_parse(char const *)" (?myproject_parse@@YAHPBD@Z
) referenced in function _main [D:\Source\myproject\build\test_myproject.vcxproj]
D:\Source\myproject\build\Debug\test_myproject.exe : fatal error LNK1120: 1 unresolved externals [D:\Source\myproject\build\test_
myproject.vcxproj]

1 个答案:

答案 0 :(得分:1)

尝试按目标名称链接您的库,也可以确保lib的源包含您期望的文件,另一种可能是没有编译符号

TARGET_LINK_LIBRARIES ( ${NAME_TEST} ${NAME_LIB} )