【问题标题】:CMake doesn't link the object files [closed]CMake不链接目标文件[关闭]
【发布时间】:2021-10-03 13:22:41
【问题描述】:

您好,我正在尝试使用 CMake 构建我的 SFML 项目,但是当我尝试使用多个源文件时,CMake 不会链接目标文件

这是我的 CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
set(CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

project(PolygonPoints)
find_package(SFML 2.5.1 COMPONENTS graphics window system audio REQUIRED)
file(
    GLOB
    SOURCES
    "src/*.hpp"
    "src/*.cpp"
)

add_executable(PolygonPoints ${SOURCES})
target_link_libraries(PolygonPoints sfml-graphics sfml-window sfml-system sfml-audio)
target_include_directories(PolygonPoints PRIVATE include)

这是我的项目结构:

PolygonPoints/
    src/
        main.cpp
        point.cpp
    include/
        point.hpp
    build/
        (...)
    CMakeLists.txt
    (...)

这是我得到的错误:

bayram@milkyway ~/Projects/PolygonPoints/build (main)> cmake .. && make && ./PolygonPoints
-- Found SFML 2.5.1 in /usr/lib64/cmake/SFML
-- Configuring done
-- Generating done
-- Build files have been written to: /home/bayram/Projects/PolygonPoints/build
Consolidate compiler generated dependencies of target PolygonPoints
[ 33%] Linking CXX executable PolygonPoints
/usr/bin/ld: CMakeFiles/PolygonPoints.dir/src/main.cpp.o: in function `main':
main.cpp:(.text+0x173): undefined reference to `Point::Point(sf::Vector2<int>, sf::Vector2<int>)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/PolygonPoints.dir/build.make:117: PolygonPoints] Error 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/PolygonPoints.dir/all] Error 2
make: *** [Makefile:91: all] Error 2

【问题讨论】:

  • 你是否在你的 point.cpp 文件中实现了Point::Point(sf::Vector2&lt;int&gt;, sf::Vector2&lt;int&gt;) 函数。也许你有一个错字。
  • 在不使用 CMake 的情况下构建项目时是否收到相同的错误消息?
  • @drescherjm 是的,我确实实现了。
  • 我会删除这个问题并提出一个新问题,其中包含一个 minimal reproducible example 没有 SFML 和 CMake。已经有一个答案和一些与 CMake 相关的 cmets。编辑会令人困惑。

标签: c++ cmake header-files sfml


【解决方案1】:

这里要小心:

file(
    GLOB
    SOURCES
    "src/*.hpp"
    "src/*.cpp"
)

据我了解,这仅在 cmake 项目配置期间运行,因此如果您稍后添加了 .cpp 文件,它将不会包含在构建中。您最好在可执行文件中明确列出您的文件,如下所示:

add_executable(PolygonPoints 
    src/main.cpp
    src/point.cpp
)

现在添加文件时,您必须编辑 add_executable,这会导致 cmake 重新评估自身并重新生成构建/制作文件(取决于您的生成器),因此文件始终按预期编译。

【讨论】:

  • 在cmet中有明确的描述,这个问题与CMake无关,没有CMake也会出现。它也与 SFML 无关。
  • "@ThomasSablik 我尝试在命令行中使用 g++ -I include/ -c src/*.cpp && g++ -lsfml-graphics -lsfml-window -lsfml-system main.o point.o 进行编译我得到了同样的错误。有趣的是,我认为问题出在 CMake"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多