Search code examples
c++cmake3dclionglfw

How to link static libraries in cmake


I am trying to link GLFW in my project. There is screenshot of my project structure: enter image description here

This is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.15)
project(testo)

set(CMAKE_CXX_STANDARD 17)

add_executable(testo main.cpp)
add_library(glfw3 STATIC main.cpp)

include_directories(lib/glfw/include/)

find_library(GLFW glfw3 lib/glfw/lib)
target_link_libraries(testo LINK_PUBLIC ${GLFW})

Howewer, when i try to run project in clion, it gives me error:

====================[ Build | testo | Debug ]===================================
"C:\Program Files\JetBrains\CLion 2019.2.5\bin\cmake\win\bin\cmake.exe" --build C:\Users\Student\testo\cmake-build-debug --target testo -- -j 2
[ 50%] Linking CXX executable testo.exe
CMakeFiles\testo.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/Student/testo/main.cpp:5: undefined reference to `glfwInit'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\testo.dir\build.make:87: testo.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:77: CMakeFiles/testo.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:84: CMakeFiles/testo.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: testo] Error 2

Solution

  • Here is some github example.
    Here is some SO question you are duplicating.

    Based on that this should look like this:

    cmake_minimum_required(VERSION 3.15)
    project(testo)
    
    set(CMAKE_CXX_STANDARD 17)
    
    find_package(GLEW REQUIRED)
    
    add_executable(testo main.cpp)
    target_link_libraries(testo PUBLIC ${GLEW_LIBRARIES})
    target_include_directories(testo PUBLIC ${GLEW_INCLUDE_DIRS})