-4
  • Why the headfiles of main.cpp only need include .h headfiles only contain declaration instead of implementation?

  • Can I write a class in a cpp file including both declaration and implementation and then include that cpp file to main.cpp as headfile?

  • How can include a headfile not in this project?

wangsquirrel
  • 135
  • 2
  • 12
  • 1
    I suggest you start by reading a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Header files will be explained there as well. – Angew is no longer proud of SO May 02 '13 at 14:58
  • 1
    Following article about source files and header might help (or not, the question is not too clear): http://www.cplusplus.com/forum/articles/10627/ – stefaanv May 02 '13 at 14:59

2 Answers2

1

Technically, a header file (or any other file you decide to #include) can contains absolutely anything that as a whole makes a complete C++ program.

What happens when the compiler (technically, a part of the compiler package called the "C preprocessor") sees a #include "somefile.h" in the source-code is that it takes that file, and essentially "pastes" it into your the main file being compiled. So you could "pretend" to be the preprocessor by opening the headerfile, marking all and then pasting it into your main file.

The point about header files is mainly to avoid copying and pasting the same bit of C++ into several source files. So for example, the declaration of a class can be put into a header file myclass.h, the actual implementation into a myclass.cpp file, and then another part of the program using myclass would just need to include the header.

Header files that are not part of your project are typically surrounded with angle brackets, #include <header.h> would include "header.h" from some other project.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

Headers are really simple. All they do is paste a copy of the code from the .h file in place of the #include.

C/C++ needs to know the size of objects or the type and count of parameters but it doesn't need to know the implementation. The default linkage of free functions is always extern. So by writing int myFunc(); you are actually writing extern int myFunc(). As long as that function is implemented in a different compilation unit (a cpp file that is compiled) that will work fine.

Yes you can #include cpp files, but if you actually compile both that your 'header.cpp' and 'main.cpp' you will encounter a multiple definition problem at link time. Simply leave the .cpp file out of your make file or project. A lot of libraries use .hpp as their extension to for C++ headers that have their entire implementation inline.

NtscCobalt
  • 1,639
  • 2
  • 15
  • 31