1

I've read a bunch questions on this site about the usage of add_executable function in CMake, but have not found an exact answer to my confusion.

My question is why we only add .cpp files in the add_executable function but not .hpp files?

I understand header files are like "indices" for functions and classes in the corresponding .cpp files. But if we don't include them in the add_executable function, how are they used in the build process?

For example, will the A.hpp file be used when another source file import A.hpp? But then A.hpp is not in the add_executable function... How does the program know where to find A.hpp?

Thanks!

1 Answer 1

4

Header files, which often have .h or .hpp extension, although not always - for example, C++ standard library headers have no extensions - are "copy-pasted" by compiler into every .cpp (or .C, or .cc) which has #include directive to include the file.

Because of that, build system, such as CMake, doesn't have to know about them when the final executable is built - their contents is already accounted for by literal inclusion of their code into .cpp file.

However, build systems need to know about those files when dependencies are specified - to ensure that the whole application is rebuilt whenever any of those files is updated, and also to provide the proper inclusion path to the compilation command.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the prompt reply. Does this mean it's not the build system's job to figure out the #include path for the .hpp files? As that's the job of the compiler?
@yuqli CMake figures out include paths by means of 'target_link_library' for headers provided by app or libraries it uses, and compiler uses predefined default paths for everything else. But that has nothing to do with executable building, so that's why add_executable doesn't have it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.