Reputation: 791
I have a very large Native C++ project with hundreds of classes each defined in their own .cpp and .h file. Nothing weird here. I have all of the classes declared in my pre-compiled header stdafx.h file and also included in the stdafx.h file as shown below (to allow Foo to reference Bar AND Bar to reference Foo).
Is this organization bad practice?
Essentially, all classes are declared and included in every object. I assume the compiler is not going to generate overhead binary by having things included which are not necessary to compiling the particular .cpp object file. As of now I'm not having any problem with compile time either. I'm just wondering if this is a bad organization for the code.
I like this layout because the stdafx.h file is essenetially a code map since all classes are declared there and it reveals the nested namespaces is an easy to read format. It also means that my individual class .h files don't require several include statements which means less code for me to maintain when making changes to filenames or directories.
stdafx.h:
#pragma once
namespace MyProject
{
class Foo;
class Bar;
}
#include "Foo.h"
#include "Bar.h"
foo.h:
#pragma once
namespace MyProject
{
class Foo
{
// Declare class members, methods, etc
}
}
foo.cpp:
#include "stdafx.h"
namespace MyProject
{
class Foo
{
// Define class members, methods, etc
}
}
Upvotes: 1
Views: 559
Reputation: 45694
A header should include everything it needs, no more, no less.
That's a basic requirement for ease-of-use and simple encapsulation.
Your example explicitly fail that point.
To detect violations, always include the corresponding header first in the translation-unit.
This is slightly modified if you use precompiled headers, in which case they have to be included first.
Pre-compiled headers should only include rarely changing elements.
Any change to the pre-compiled header or its dependencies will force re-compilation of everything, which runs counter to using one at all.
Your example fails that point too.
All in all, much to improve.
Upvotes: 0
Reputation: 38959
In my mind there are 4 key factors here:
#include "x.h"
embeds all the code in x.h at that line. If the project is going to grow substantially have a care for how you're going to impact future compile times.Foo
and Bar
Stability: If Foo
and Bar
are changing you're going to have to keep recompiling stdafx.hIf you feel your pros outweigh the cons listed here, there's nothing illegal about what you're doing so go for it!
Upvotes: 2