CMake + Qt Creator: Add header files to project files

The Quantum Physicist picture The Quantum Physicist · Feb 21, 2017 · Viewed 9.8k times · Source

If I have .h and .cpp files in the directory src, where the .cpp files include the .h files, using these commands in CMake:

aux_source_directory(src SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})

And opening that CMake file in Qt Creator, gets all the files (sources + headers) in the list of project files (the file tree on the left by default).

Now, on the other hand, if I put all the .h files in a directory include, and use this:

include_directories(include)
aux_source_directory(src SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})

The header files disappear from the project files!

How can I keep the header files in that directory, and still have them listed in Qt Creator's project files?

Answer

Torbjörn picture Torbjörn · Feb 21, 2017

You shouldn't use aux_source_directory() for your task. That command is for something different. Just list the source files (or put them in a variable).

You shouldn't use include_directory() for defining include directories any more. This command will just populate the -I flag of the compiler. Define a variable with the header files and add that to the executable.

In case you don't want to list every file manually, use file(GLOB ...). But be aware of the caveats mentioned frequently all over the web with using that command.

Afterwards, tell CMake to populate the -I flag only for that executable with the include directory. That way, other targets don't get polluted by includes, they shouldn't use.

set(SOURCES
    src/main.cpp
    src/whatever.cpp)
set(HEADERS
    include/whatever.h)
add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})
target_include_directories(${PROJECT_NAME} PUBLIC include)