Reputation: 1039
I know that this is a silly question, but I am new to c++ and it's development environment and I want to learn it the right way.
I am trying to learn how CMake works. Using CLion (which dynamically generated the CMakeList.txt
), I saw that when a class is created, both the .cpp
and .h
are added to the target executable. But when removing the .h
file from the add_executable
call, the code compiled just fine, even tho in main.cpp
there was a #include
reference to that header file.
My question is if adding headers to the target executable is optional or not? I normally use VSCode which doesn't generate the CMakeList.txt
for me and I wouldn't want to make a habit of not including headers to the target executable if I am supposed to do so.
Upvotes: 2
Views: 1995
Reputation: 2598
Generally, I believe you're supposed to
SET_SOURCE_FILE_PROPERTIES(${header_files} PROPERTIES HEADER_FILE_ONLY ON)
then
LIST (APPEND ${project_sources} ${header_files})
. Compile with ${project_sources}.
Upvotes: 1
Reputation: 238461
add_executable
simply takes a list of files which it passes on to the compiler. The compiler ignores any file with a conventional header suffix (maybe all suffixes that it doesn't recognise as source file). As such, it is not necessary to list header files, nor will listing them cause problems - as far as compilation is concerned.
Some IDE may use the listed header files for some internal purposes. I'm not sure if Clion does; its behaviour may be to facilitate the use of another IDE.
Upvotes: 1