CMake linking glfw3 lib error

2019-07-31 16:56发布

问题:

i'm working with CLion, and I'm writing a program using the glfw3 lib.(http://www.glfw.org/docs/latest/)

I installed and did everything correctly for the lib i have the .a and .h files in:

/usr/local/lib/libglfw3.a

/usr/local/include/.h(all files)

I'm trying to use the library now, but i'm getting the linker error:

undefined reference to 'glViewport' etc. etc. all the functions i'm using

I added the lib path to the make file, I can't understand what i'm doing wrong, my CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.6)
project(testing)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp examples.h)

add_executable(testing ${SOURCE_FILES})
target_link_libraries(testing /usr/local/lib/libglfw3.a)
target_link_libraries(testing /usr/local/lib/libTest.a)

target_link_libraries(testing pthread)

any help will be appreciated.

Thanks!

回答1:

You should not hard code absolute paths into your CMake files. This renders CMake useless.

In the documentation of GLFW on how to link against it, there it is explicitly written:

find_package(glfw3 3.2 REQUIRED)
find_package(OpenGL REQUIRED)

target_include_directories(myapp PUBLIC ${OPENGL_INCLUDE_DIR})
target_link_libraries(myapp
                      glfw
                      ${OPENGL_gl_LIBRARY})

Moreover, you can replace

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

with

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

and CMake will figure out the correct compiler flag automatically depending on the compiler currently in use.