How to compile GLUT + OpenGL project with CMake and Kdevelop in linux?

Solution 1:

find_package(OpenGL) will find the package for you, but it doesn't link the package to the target.

To link to a library, you can use target_link_libraries(<target> <item>). In addition, you also need to set the include directory, so that the linker knows where to look for things. This is done with the include_directories.

An example CMakeLists.txt which would do this looks something like this:


cmake_minimum_required(VERSION 2.8)

project(testas)
add_executable(testas main.cpp)
find_package(OpenGL REQUIRED)
find_package(GLUT REQUIRED)
include_directories( ${OPENGL_INCLUDE_DIRS}  ${GLUT_INCLUDE_DIRS} )

target_link_libraries(testas ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} )

If OpenGL is a necessity for your project, you might consider either testing OpenGL_FOUND after the find_package(OpenGL) or using REQUIRED, which will stop cmake if OpenGL is not found.

For more information and better examples:

  • CMake 2.8 documentation, target_link_libraries
  • CMake 2.8 documentation, find_package
  • CMake wiki: how to find libraries
  • Forum post with solution: cmake and opengl
  • Tutorial for CMake by swarthmore.edu

In particular, the CMake wiki and cmake and opengl links should give you enough to get things working.

Solution 2:

In recent versions of CMake (3.10+) there is a new way to use OpenGL using a so-called IMPORTED target:

cmake_minimum_required(VERSION 3.10)

project(testas)
add_executable(testas main.cpp)
find_package(OpenGL REQUIRED COMPONENTS OpenGL)
find_package(GLUT REQUIRED)

add_dependencies(testas OpenGL::OpenGL)
include_directories(${GLUT_INCLUDE_DIRS} )

target_link_libraries(testas OpenGL::OpenGL ${GLUT_LIBRARY} )

At the moment the only practical difference seems to be on Linux (where GLVND is used if available), but presumably this solution should be more future-proof, as CMake has more information about your intentions and other tools parsing your CMakeFiles will better understand the dependency tree.

Solution 3:

As of recently you can use GLUT::GLUT:

cmake_minimum_required(VERSION 2.8)

project(testas)

find_package(OpenGL REQUIRED)
find_package(GLUT REQUIRED)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} OpenGL::GL GLUT::GLUT)