开发者

C++ header file convention

开发者 https://www.devze.com 2022-12-13 05:44 出处:网络
I am working on a small game using C++, and I used Eclipse CDT\'s class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.

I am working on a small game using C++, and I used Eclipse CDT's class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.

So if I followed the template, I'd have 开发者_JAVA百科a .cpp file filled with the methods declarations, and a .cpp file with method bodies. However, I can't include a .cpp file within another.

So what is the convention in C++ with classes and include files? What I did was fill in the method bodies right under the class declaration in the .h file, and deleted the .cpp file.


You don't have to include the .cpp file. Including the .h file is all it takes. .h means header, ie, all it should have is function / object definitions. The actual implementations go in the .cpp file of the same name. The linker will deal with straightening it out for you.

The header file contains declarations (also known as prototype). Inclusion of the header lets the program know "I declare something that looks like this exists".

The user of headers saves us the effort of declaring methods all over the place in our code files - we just do it once, then import the file.

The .c/.cpp/.cc file includes the definition - which tells the program what the function does.

You do not have to "include" .c files because that's what the compiler does - it compiles all your .c files into machine code.


One more thing you can do is while creating a header file is to use the preprocessor directive ifdef and endif. This will prevent your header file being included multiple times. This is a standard practice which I use whenever I create a new header file.


I'm not quite sure I understand. The header files defines what the class is and can do, and you include that into any source files that need to use the class.

The source file implements how the class does its action.

However, you can include a .cpp into another (you can include anything into anything), but you don't need to.

0

精彩评论

暂无评论...
验证码 换一张
取 消