首页 > 解决方案 > 通过 CMake 将依赖项添加到 C++ 项目

问题描述

我正在尝试在GLFW中运行示例代码。我正在尝试使用 CMake 构建项目。我在stackoverflow中浏览了很多帖子。但我无法将 GLFW 库正确添加到项目中。你能帮我配置 CMakeLists.txt 文件吗?

项目结构

CMakeLists.txt

cmake_minimum_required(VERSION 3.17)
project(cmake_testapp)

set(CMAKE_CXX_STANDARD 14)

include_directories(includes/GLFW)

LINK_DIRECTORIES(lib)
add_executable(cmake_testapp main.cpp)
TARGET_LINK_LIBRARIES(cmake_testapp glfw3)

主文件

#include <glfw3.h>

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

构建时出错:

====================[ Build | cmake_testapp | Debug ]===========================
"C:\Program Files\JetBrains\CLion 2020.2.4\bin\cmake\win\bin\cmake.exe" --build C:\Users\User\CLionProjects\cmake_testapp\cmake-build-debug --target cmake_testapp -- -j 6
[ 50%] Linking CXX executable cmake_testapp.exe
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: CMakeFiles\cmake_testapp.dir/objects.a(main.cpp.obj): in function `main':
C:/Users/User/CLionProjects/cmake_testapp/main.cpp:26: undefined reference to `_imp__glClear@4'
collect2.exe: error: ld returned 1 exit status
CMakeFiles\cmake_testapp.dir\build.make:105: recipe for target 'cmake_testapp.exe' failed
CMakeFiles\Makefile2:94: recipe for target 'CMakeFiles/cmake_testapp.dir/all' failed
mingw32-make.exe[3]: *** [cmake_testapp.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/cmake_testapp.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/cmake_testapp.dir/rule] Error 2
mingw32-make.exe: *** [cmake_testapp] Error 2
CMakeFiles\Makefile2:101: recipe for target 'CMakeFiles/cmake_testapp.dir/rule' failed
Makefile:137: recipe for target 'cmake_testapp' failed

标签: c++cmake

解决方案


推荐阅读