Search code examples
c++openglcmakeglfw

C++ Library linking issue


I'm trying to follow a tutorial from (https://learnopengl.com/Getting-started/Creating-a-window).

I've already compiled a static GLFW library, set up a CMake file etc. But when I try to compile my test app, I get errors like undefined reference to 'glfwInit'.

The tutor says:

If you try to run the application now and it gives a lot of undefined reference errors it means you didn't successfully link the GLFW library.

Unfortunately I don't understand what's wrong.

I would be thankful if you help me to figure out this problem.

Project structure:

  • include
    1. glad.h
    2. glfw3.h
    3. glfw3native.h
    4. khrplatform.h
  • lib
    1. libglfw3.a
  • src
    1. glad.c
    2. main.cpp

CMakeLists.txt

My cmake file:

cmake_minimum_required(VERSION 3.15)
project(testGlFW)

set(CMAKE_CXX_STANDARD 14)

link_directories(${PROJECT_SOURCE_DIR}/lib)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
set(CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} -ldl")

include_directories(${PROJECT_SOURCE_DIR}/include)

add_executable(testGlFW src/main.cpp)

And here is a main.cpp:

#include "glad/glad.h"
#include "GLFW/glfw3.h"


int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    return 0;
}

Solution

  • You need to actually link the GLFW library. Add this last in your CMakeLists.txt:

    target_link_libraries(testGlFW PRIVATE glfw3)