I am new to CMake and would like to ask if somebody can help in the following problem.
I have C++ source and header files in their respective folders and now, I want to make a CMake text file that recursively searches for them.
Currently, I am doing it in this way:
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(CarDetectorDAISY)
file(GLOB_RECURSE SRCS *.cpp)
file(GLOB_RECURSE HDRS *.h)
ADD_EXECUTABLE(stereo_framework ${SRCS} ${HDRS})
TARGET_LINK_LIBRARIES(stereo_framework)
This creates my CarDetectorDAISY.sln solution file and when I try to build it, it shows an error that header files are not found (No such file or directory).
It would be really grateful if someone can please help me. Thanks.
You're probably missing one or more
include_directories
calls. Adding headers to the list of files in theadd_executable
call doesn't actually add then to the compiler's search path - it's a convenience feature whereby they are only added to the project's folder structure in IDEs.So, in your root, say you have /my_lib/foo.h, and you want to include that in a source file as
Then in your CMakeLists.txt, you need to do:
If, instead you just want to do
then in the CMakeLists.txt, do
I should mention that
file(GLOB...)
is not the recommended way to gather your list of sources - you should really just add each file explicitly in the CMakeLists.txt. By doing this, if you add or remove a source file later, the CMakeLists.txt is modified, and CMake automatically reruns the next time you try and build. From the docs forfile
:Just to further clarify one point in Fraser's answer:
Headers should not be passed to
ADD_EXECUTABLE
.The reason is that the intended compilation command on Linux for example is just:
and not:
The C pre-processor then parses
mylib.c
, and sees a#include "mylib.h"
, and uses it's search path for those files.By using
include_directories
instead, we modify the cpp preprocessor search path instead, which is the correct approach. In GCC, this translates to adding the-I
flag to the command line: