tribbloid
tribbloid

Reputation: 3838

Why CMake fail to recognise a library despite that it has been added by 'include_directories'?

My CMakeList file defined a list of directory that should be included in the build path:

set(CMAKE_CXX_STANDARD 11)

include_directories(lib)
include_directories(lib/freeglut)
include_directories(lib/freeglut/include)
include_directories(lib/freeglut/include/GL)
include_directories(lib/matrix)
include_directories(lib/mavlink)
include_directories(lib/mavlink/common)
include_directories(src)
include_directories(src/Drawing)
include_directories(src/Math)
include_directories(src/MavlinkNode)
include_directories(src/Simulation)
include_directories(src/Utility)
...

all dependent files are under /lib. When I run CMake CMakeList.txt & make, I got the following error:

[100%] Linking CXX executable FCND_Controls_CPP
CMakeFiles/FCND_Controls_CPP.dir/src/main.cpp.o: In function `main':
/home/peng/git-drone/__Udacity__/FCND-Controls-CPP/src/main.cpp:68: undefined reference to `glutTimerFunc'
/home/peng/git-drone/__Udacity__/FCND-Controls-CPP/src/main.cpp:70: undefined reference to `glutMainLoop'
...

While both functions glutTimerFunc and glutMainLoop are under 'lib/freeglut/include/GL/freeglut.h'. Yet either CMake and make is ignoring them. Why this could happen and what should I do to fix them?

I'm using cmake 3.9.1, I've tried 2 backends: gcc/g++ and clang/clang++ and both gave the same error.

Upvotes: 1

Views: 340

Answers (1)

Samaursa
Samaursa

Reputation: 17197

You are using include_directories which are directories for the compiler to check for includes. What you should be using is target_link_libraries.

However, since you are using a known library, you'll want to do something like this (you can find this information in the FindGLUT.cmake file under the cmake-modules directory):

find_package(GLUT REQUIRED)
target_include_directories(your_exe PUBLIC ${GLUT_INCLUDE_DIR}) # could also be PRIVATE, depending on usage
target_link_libraries(your_exe ${GLUT_LIBRARY} )

Note that you'll also need to do the same with OpenGL libraries with the cached variables ${OPENGL_INCLUDE_DIR} and ${OPENGL_LIBRARIES}.

Note: Try to avoid using include_directories (without target) as that is considered the older style and has the drawback of pollutating the include directories of all targets.

Upvotes: 1

Related Questions