2
votes

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?

2

2 Answers

0
votes

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
)
5
votes

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)