CMake + Qt Creator: Add header files to project files
Solution 1
I add my header files always explicit to avoid any surprise. But on MacOS using QtCreator 4.2.0 and cmake 3.7.1 I can't reproduce your issue.
However I recommend to use following structure to know which files are within project and to trigger update of cmake's data during update of CMakeLists.txt.
In project/CMakeLists.txt:
add_subdirectory(src)
include_directory(include)
add_executable(foo ${SRC_LIST})
In project/src/CMakeLists.txt:
set(SRC_LIST
${SRC_LIST}
${CMAKE_CURRENT_SOURCE_DIR}/a.cpp
${CMAKE_CURRENT_SOURCE_DIR}/b.cpp
PARENT_SCOPE
)
Solution 2
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)
The Quantum Physicist
I did a PhD of particle physics back in the days, and then left academia to start a professional career with software development, because I love it. I still contribute to science by leading software development efforts for scientific experiments. I love science, but I love programming even more :-)
Updated on June 05, 2022Comments
-
The Quantum Physicist almost 2 years
If I have
.h
and.cpp
files in the directorysrc
, 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 directoryinclude
, 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?