【问题标题】:Undefined reference to function CMake对函数 CMake 的未定义引用
【发布时间】:2016-07-22 15:40:30
【问题描述】:

我正在尝试学习 CMake,但我得到一个未定义的引用 ... 链接器错误 我有一个带有子目录的目录。 他们每个人都有自己的 CMakeLists.txt

test
|----main.cpp
|----CMakeLists.txt
|----test2
     |----foo.hpp
     |----foo.cpp
     |----CMakeLists.txt

用于测试的 CMakeLists.txt 是:

cmake_minimum_required(VERSION 3.5)
project(tests)

add_subdirectory(test2)
set(SOURCE_FILES main.cpp)
add_executable(tests ${SOURCE_FILES})

test2 的 CMakeLists.txt 是:

set(test2_files
        foo.cpp
        foo.hpp
        )
add_library(test2 ${test2_files})

foo.cpp 实现了一个在foo.hpp 中定义的函数 对于这个函数,我得到了未定义的参考错误。 我究竟做错了什么?我怎样才能摆脱这个链接器错误

编辑:我的 CMakeLists.txt 现在看起来像这样,但我仍然收到链接器错误:

project(tests)

cmake_minimum_required(VERSION 2.8)

set(SOURCE_FILES main.cpp)

include_directories(test2)
link_directories(test2)

add_subdirectory(test)

add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )

target_link_libraries(${PROJECT_NAME} test2)

我也试过用绝对路径代替test2

编辑: 解决了它只是test2的CMakeLists.txt中的一个错字。

【问题讨论】:

    标签: c++ build linker cmake


    【解决方案1】:

    确保您的测试 CMakeLists.txt 链接到创建的库。

    project(test)
    
    cmake_minimum_required(VERSION 2.8)
    
    set(SOURCE_FILES main.cpp)
    
    include_directories( test2 )
    
    #here
    link_directories(test2)
    
    add_subdirectory(test2)
    
    add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
    
    #and here
    target_link_libraries( ${PROJECT_NAME} test2 )
    

    【讨论】:

    • 如果我使用这个我会收到这个错误:/usr/bin/ld: cannot find -ltest2
    • 添加了一行,给顶层一个本地链接目录。
    • 您希望它是 *.a 还是 *.so?此实现在构建目录中生成一个 *.a 文件。
    • 我用 link_directories(test2) 也用绝对路径试过,但它一直说“udefined reference to...”
    • @Exagon。你让它工作了吗?抱歉,我已经离开电脑几天了。
    【解决方案2】:

    函数add_subdirectory($dir) 不会自动添加$dir 以包含目录和链接目录。要使用库test2,您应该在test 目录的CMakeLists.txt 中手动进行:

    include_directories(test2/)
    link_directories(test2/)
    

    然后,将您的可执行文件与test2 库链接以获取函数定义。添加到test目录的CMakeLists.txt:

    target_link_libraries(tests test2)
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 2012-10-14
      • 2020-06-26
      • 2015-12-06
      • 2018-01-01
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多