CMAKE链接外部c库

时间:2011-01-24 20:32:48

标签: c++ linker cmake

嗨,基本上我正在尝试使用here中的svm。它是用C语言编写的,并给出了如何在c ++中使用它的说明:

  
      
  • 将“svm_learn.c”,“svm_common.c”和“svm_hideo.c”编译为
      C代码。
  •   
  • 要调用的C ++程序svm_learn / 8和classify_example / 2   来自(或classify_example_linear / 2)   需要包括以下内容   头:

         

    extern“C”{    #include“svm_common.h”    #include“svm_learn.h”    }

  •   
  • 将“svm_learn.o”,“svm_common.o”和“svm_hideo.o”链接到您的程序。

  •   

所以我编译了上面提到的文件并获得了所需的.o文件。 比我补充说:

SET( svm_lib_light_obj
    E:\framework\svm_light\build\svm_learn.o
    E:\framework\svm_light\build\svm_common.o
    E:\framework\svm_light\build\svm_hideo.o
)

ADD_LIBRARY(
    svm_lib_light
    STATIC
    EXCLUDE_FROM_ALL
    ${svm_lib_light_obj}
)

SET_SOURCE_FILES_PROPERTIES(
  ${svm_lib_light_obj}
  PROPERTIES
  EXTERNAL_OBJECT true # to say that "this is actually an object file, so it should not be compiled, only linked"
  GENERATED true       # to say that "it is OK that the obj-files do not exist before build time"
  )

SET_TARGET_PROPERTIES(
  svm_lib_light
  PROPERTIES
  LINKER_LANGUAGE C # Or else we get an error message, because cmake can't figure out from the ".o"-suffix that it is a C-linker we need.
  ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib
  )

所以现在我只需要包含提到的.h文件。我将它们添加到我的其他源文件中:

ADD_EXECUTABLE ( MYProgramm
            ...
            #other source files
            ...
            src/svm_common.h
            src/svm_learn.h
)

不幸的是它不起作用。从这些.h文件调用任何函数会导致链接器错误LNK2001,LNK1120。 我猜我必须告诉cmake这些.h文件是.o文件的前端。但是如何?

1 个答案:

答案 0 :(得分:5)

最好的方法是将这些C文件添加到项目中:

SET(SVM_LIGHT_SRC_DIR "E:/framework/svm_light")

INCLUDE_DIRECTORIES(${SVM_LIGHT_SRC_DIR})

ADD_LIBRARY(
    svm_lib_light
    ${SVM_LIGHT_SRC_DIR}/svm_learn.c
    ${SVM_LIGHT_SRC_DIR}/svm_common.c
    ${SVM_LIGHT_SRC_DIR}/svm_hideo.c
)

ADD_EXECUTABLE ( MYProgramm
            ...
            #other source files
            ...
)

TARGET_LINK_LIBRARIES(MYProgram svm_lib_light)
相关问题