473,672 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

General hints on what to #include in what

One thing i do know for sure. When one creates a CPP file,
one needs to include the H file. Now, having said that, i
wonder if there are some general hints, requirements or
standard guide lines on what and how to include.

Suppose that we have a project consisting of a number of
classes and structs. Some of them using the others, some
using all of them. What is a good approach when including?

--
Vänligen Kerstin Viltersten
(The Cool Giraffe)
Feb 25 '07 #1
8 2137
The Cool Giraffe wrote:
One thing i do know for sure. When one creates a CPP file,
one needs to include the H file. Now, having said that, i
wonder if there are some general hints, requirements or
standard guide lines on what and how to include.

Suppose that we have a project consisting of a number of
classes and structs. Some of them using the others, some
using all of them. What is a good approach when including?
It's a good question. Here's a good set of rules.

1) Every header file should be able to be compiled on its own. So if
your header defines a class which uses std::string, say, then that
header file should include <string>. If it uses MyStruct then it should
include "MyStruct.h ". It is really annoying to have a header file and
then have to work out what other header files you have to include before
you include the first header file (unfortunately Microsoft are bad
offenders in this regard).

2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file. So if you have widget.h and
widget.cpp then widget.cpp should include widget.h as its very first
include, before absolutely anything else. That way if widget.h isn't
including something that it should you will find out because of a
compiler error.

3) But only include what you need to get compilation working. It's a
mistake to include "X.h" in "Y.h" just because you think that whoever is
using "Y.h" will probably want "X.h" as well. Leave that decision to the
person actually including the header files.

4) After you've followed rules 1 and 2 then include every header you
need to get the compilation of each cpp file working, but again, no more.

Unfortunately there is no automatic way to ensure that you don't include
stuff you don't need in either cpp or header files, so I usually review
header and cpp files from time to time to make sure I'm not including
anything I don't need.

john
Feb 25 '07 #2
On 25 Feb, 10:49, "The Cool Giraffe" <giraf...@vilte rsten.comwrote:
One thing i do know for sure. When one creates a CPP file,
one needs to include the H file. Now, having said that, i
wonder if there are some general hints, requirements or
standard guide lines on what and how to include.

Suppose that we have a project consisting of a number of
classes and structs. Some of them using the others, some
using all of them. What is a good approach when including?
A few rules I believe are worth sticking to with headers:

1. When you have classes and structs that know about other classes and
structs, use forward declarations whenever you can to reduce the
number of headers included in other headers. See
http://www.parashift.com/c++-faq-lit...html#faq-39.11
and the ones that follow it. Although that FAQ talks about resolving a
circular dependency, it describes the general principle of forward
declarations and how they are used.

2. The point above will hopefully reduce the number of includes you
need within a particular header. However, *always* make sure that a
header *does* include everything it needs to be a stand-alond
compileable unit. A source file that contains nothing except #include
"my_header. h" should compile with no errors. Example (untested but I
think simple enough to make the point):

// my_header.h original
struct person
{
std::string name;
};

// test_my_header. cpp original
#include "my_header. cpp"

test_my_header. cpp will not compile. You will get an error because the
compiler does not know what std::string is. One solution is to change
test_my_header. cpp:

// test_my_header. cpp modified in an un-good way
#include <string>
#include "my_header. cpp"

Now it compiles. But if you follow this approach, you force yourself
and everybody else who ever uses my_header.h to have to remember to
include <stringbefore my_header.h *every time* they use it. Much
better is to modify my_header.h

// my_header.h modified in a good way
#include <string>
struct person
{
std::string name;
};

Now the original version of test_my_header. cpp will compile cleanyl,
and users of your header can simply include it without needing to jump
through any other hoops.

3. Always use include guards in every header. Doesn't seem to be a FAQ
on that, but wikipedia will suffice http://en.wikipedia.org/wiki/Include_guard.
No, my example above does not follow this advice. That was for clarity
in making the point. In the real world I would certainly put an
include guard in my_header.h.

4. Don't put using directives or using declarations in headers (at
least not at global scope - they can be necessary inside class
definitions). Using directives and declarations have pros and cons and
whether to use them or not needs to be judged on a case by case basis.
If you put one in a header, you force its use on everyone who ever
includes that header, whether they want it or not. Don't do that - let
them decide for themselves.

HTH
Gavin Deane

Feb 25 '07 #3
John Harrison wrote/skrev/kaita/popisal/schreibt :
The Cool Giraffe wrote:
>One thing i do know for sure. When one creates a CPP file,
one needs to include the H file. Now, having said that, i
wonder if there are some general hints, requirements or
standard guide lines on what and how to include.

Suppose that we have a project consisting of a number of
classes and structs. Some of them using the others, some
using all of them. What is a good approach when including?

It's a good question. Here's a good set of rules.

1) Every header file should be able to be compiled on its own. So if
your header defines a class which uses std::string, say, then that
header file should include <string>. If it uses MyStruct then it
should include "MyStruct.h ". It is really annoying to have a header
file and then have to work out what other header files you have to
include before you include the first header file (unfortunately
Microsoft are bad offenders in this regard).

2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file. So if you have widget.h and
widget.cpp then widget.cpp should include widget.h as its very first
include, before absolutely anything else. That way if widget.h isn't
including something that it should you will find out because of a
compiler error.

3) But only include what you need to get compilation working. It's a
mistake to include "X.h" in "Y.h" just because you think that whoever
is using "Y.h" will probably want "X.h" as well. Leave that decision
to the person actually including the header files.

4) After you've followed rules 1 and 2 then include every header you
need to get the compilation of each cpp file working, but again, no
more.
Unfortunately there is no automatic way to ensure that you don't
include stuff you don't need in either cpp or header files, so I
usually review header and cpp files from time to time to make sure
I'm not including anything I don't need.

This pretty much answered my question. Thanks!

--
Vänligen Kerstin Viltersten
(The Cool Giraffe)
Feb 25 '07 #4
John Harrison <jo************ *@hotmail.comwr ote:
1) Every header file should be able to be compiled on its own. So if
your header defines a class which uses std::string, say, then that
header file should include <string>. If it uses MyStruct then it should
include "MyStruct.h ". It is really annoying to have a header file and
then have to work out what other header files you have to include before
you include the first header file (unfortunately Microsoft are bad
offenders in this regard).

2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file. So if you have widget.h and
widget.cpp then widget.cpp should include widget.h as its very first
include, before absolutely anything else. That way if widget.h isn't
including something that it should you will find out because of a
compiler error.

3) But only include what you need to get compilation working. It's a
mistake to include "X.h" in "Y.h" just because you think that whoever is
using "Y.h" will probably want "X.h" as well. Leave that decision to the
person actually including the header files.

4) After you've followed rules 1 and 2 then include every header you
need to get the compilation of each cpp file working, but again, no more.

Unfortunately there is no automatic way to ensure that you don't include
stuff you don't need in either cpp or header files, so I usually review
header and cpp files from time to time to make sure I'm not including
anything I don't need.
While I agree in general, sometimes you may need to include additional
headers in order to have a truly portable program. Since standard
library headers are allowed to include other standard headers, it makes
it easy to forget one.

The main example I can think of is omitting #include <ostreamwhen it
is needed, since many implementations will implicitly include it when
#including <iostream>. I had a program that used std::endl and compiled
fine on Windows. When I had to move it to HP-UX, I found that I had to
explicitly #include <ostreamas well as <iostream>.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Feb 27 '07 #5
On Sun, 25 Feb 2007 11:05:25 GMT, John Harrison wrote:
>Here's a good set of rules.

1) Every header file should be able to be compiled on its own. So if
your header defines a class which uses std::string, say, then that
header file should include <string>. If it uses MyStruct then it should
include "MyStruct.h ".
'uses' means uses as data member. Otherwise a forward declaration is
sufficient, even if you pass or return by value.
>2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file.
But do this only to test header includes. Otherwise always include
system and library headers before your own.

Best regards,
Roland Pibinger
Feb 27 '07 #6
On 27 Feb, 22:06, rpbg...@yahoo.c om (Roland Pibinger) wrote:
2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file.

But do this only to test header includes. Otherwise always include
system and library headers before your own.
Why?

Gavin Deane

Feb 28 '07 #7
Gavin Deane <de*********@ho tmail.comwrote:
On 27 Feb, 22:06, rpbg...@yahoo.c om (Roland Pibinger) wrote:
>2) Assuming that you are working on the one header file for each cpp
file (which is a reasonable rule as well) then the best way to insure
that you follow rule 1 is to include a header file as the very first
header file in it's corresonding cpp file.

But do this only to test header includes. Otherwise always include
system and library headers before your own.

Why?
My guess is that if you have some funky #defines, then it would prevent
changing the meaning of system headers. However, IIRC, you are only
allowed to redefine keywords if you do not include those headers.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Feb 28 '07 #8
On 28 Feb, 18:35, ricec...@gehenn om.invalid (Marcus Kwok) wrote:
GavinDeane<dean e_ga...@hotmail .comwrote:
On 27 Feb, 22:06, rpbg...@yahoo.c om (Roland Pibinger) wrote:
<snip>
always include
system and library headers before your own.
Why?

My guess is that if you have some funky #defines, then it would prevent
changing the meaning of system headers. However, IIRC, you are only
allowed to redefine keywords if you do not include those headers.
Doesn't sound like much of a reason to me. I would expect redefining
keywords to be something that happens rarely, if ever - certainly not
commonplace enough to be justifiable as the basis for this sort of
guideline.

But then, Roland Pibinger could have had a different reason in mind.

Gavin Deane

Feb 28 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2317
by: Terje Slettebø | last post by:
Hi. I'm new here, and sorry if this has been discussed before; I didn't find it searching the PHP groups. (I've also read recommendations to cross-post to the other PHP groups, but if that is discouraged, please let me know. At the same time, please then let me know which of the many PHP groups to post to. :) ) In PHP5, you can provide "type hints" for functions, like this:
1
1800
by: jason | last post by:
Hello everyone, I have some general questions about the DataTable object, and how it works. Moderately new to C#, I have plenty of texts describing the language, but not so much to reference ADO.NET objects (only the MSDN help files). I have written a C# Class Library that is responsible for encapsulating database information. All the objects work just fine for singleton record insert, update, select, and delete operations. But now we...
3
1392
by: Square eyes | last post by:
Hi, I'm working on a program which scans .Net programs and gives hints and tips. At the moment, it can spell check forms, reports and code and some hints might include something like str.Replace("Original", "New") should read: str=str.Replace("Original", "New") Hopefully you get the idea. The question is, do you have any hints or tips
6
1860
by: gk245 | last post by:
Basically, i want to make a function that will receive a sentence or phrase, and count its words. It would start like this (i think): #include <stdio.h> int count ( char sentence ) { char string ;
25
2486
by: lovecreatesbeauty | last post by:
Could you talk something about the general rules on the interface (function) design in C program that recognized publically? Or introduce some good advice of yourself. How do you think about some of those advices like following? a. keep the interface clean and clear (What does clean or clear mean and how to achieve that?). b. avoid using static variables in local function if possible. c. avoid using global variables for local function...
94
4720
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
37
7154
by: dmoran21 | last post by:
I am a mathematician trying to write a program in C to do some curve fitting. When I get to the point where I attempt to enter data in my arrays, I get a General Protection Exception error message. What is this and how can I fix it. I am writing in Turbo C++. My source code is below. #include <stdio.h> #include <stdlib.h> #include <math.h>
3
1255
by: sromano | last post by:
vector<Log_Entry> parse(string); This function should do the following: * Open a log file specified by the parameter name (File I/O). * Read lines from the opened file. * Create a Log_Entry object passing the line just input. * Push each List_Entry object onto a vector. * Return the vector of Log_Entrys.
4
1217
by: Daniel Loose | last post by:
Hello, I have a page containing 7 iframes. Each document is created through PHP, 8 in total. I had performance issues which I could solve through Wincachegrind - now according to it, each of the 8 takes only about 20ms, i.e. the whole page should be loaded in less 0.1 seconds. In fact, it takes more than 5 seconds to load. The HTML is pretty simple. I wonder how I can detect the bottleneck reason? Any hints? Is there any general...
0
8406
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8831
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8609
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8683
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7449
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4230
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1819
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.