Clarification on a header without #includes - c++

I was reading some code from the Doom 3 SDK ( in a VS solution ) when I found a header like this:
#ifndef __PLAYERICON_H__
#define __PLAYERICON_H__
class idPlayerIcon {
public:
idPlayerIcon();
~idPlayerIcon();
...... // omitted
public:
playerIconType_t iconType;
renderEntity_t renderEnt;
qhandle_t iconHandle;
};
#endif /* !_PLAYERICON_H_ */
The header has no forward class declaration nor #includes so, in my experience it should lead to an error like: Undeclared Identifier or Syntax error, cause renderEntity_t and qhandle_t are not "seen".
So how can this compile correctly?
Thank you in advance for the answers.

Because every time it is included, the needed entities are forward declared/included right before it, so everything is defined at the point of inclusion. As you correctly say, it will not work any other way.

I guess they include other headers before including this one.

Since this is a header file it's likely there is an order to their includes elsewhere (where this file is used perhaps?). As long as renderEntity_t and qhandle_t make it into the symbol table prior to this file being included it doesn't matter.

Is there something called stdafx.h? Most VS projects have these.
It would simply be a header that includes all the needed files for your application to reduce compile time from including headers.
So it would contain something like this:
#ifndef _STDAFX_H_
#define _STDAFX_H_
#include "playerIconAndOtherVariables.h"
#include "thatFileYouListed.h"
#endif

Related

About headers, forwards and how to organize a lot of includes

I have 3 classes (it could be 300) , each one with its own header and implementation.
I'd like to write an 'elegant' way to organize the way I load of any class needed by every class of the three. Maybe this example helps...
I have : class1 class2 class3
Every header has:
#ifndef CLASS#_H
#define CLASS#_H
#define FORWARD_STYLE
#include "general.h"
#endif
Every implementation has:
#define DIRECT_STYLE
#include "general.h"
OK
I'm going to write a 'general.h' file in which I'd have :
#ifndef DIRECT_STYLE
#ifndef CLASS1_H
#include "class1.h"
#endif
#ifndef CLASS2_H
#include "class2.h"
#endif
#ifndef CLASS3_H
#include "class3.h"
#endif
#endif
#ifndef FORWARD_STYLE
class Class1;
class Class2;
class Class3;
#endif
// a lot of other elements needed
#include <string.h>
#include <stdio.h"
....
#include <vector.h"
( all the class I need now and in the future )
This is a good structure ? Or I'm doing some idiot thing ?
My goal is having one unique 'general.h' file to write all the elemenst I need...
Are this to work fine ?
Thanks
The basic rules to follow are:
Let each of your source file include all the header files it needs for getting compiled in a standalone manner. Avoid letting the header files include in the source file indirectly through other files.
If you have constructs which will be needed across most source files then put them in a common header and include the header in Only in those source files which need it.
Use Forward declarations wherever you can.There are several restrictions of when you can get away using them,read this to know more about those scenarios.
Overall it is a good idea to avoid including unnecessary code in source files through a common header because it just results in code bloat, so try and keep it to a minimum. Including a header just actually copy pastes the entire header to your source file and Including unnecessary files has several disadvantages, namely:
Increase in compilation time
Pollution of global namespace.
Potential clash of preprocessor names.
Increase in Binary size(in some cases though not always)
This might like a fine idea now, but won't scale and should be avoided. Your general.h file will include a vast amount of files, and thus all files that include it will (a) take ages to compile or not compile at all due to memory restrictions and (b) will have to be re-compiled every time anything changes.
Directly include the headers you need in each file, and define a few forward declaration files, and you should be fine.
The #define in a header will probably be ok, but it can propagate through lots of sources and potentially cause problems. More seriously, any time general.h or any of its includes change your entire project rebuilds. For small projects this isn't an issue, for larger projects it will result in unacceptable build times.
Instead, I utilize a few guidelines:
In headers, forward declare what you can, either explicitly or with #include "blah_fwd.h" as seen in the standard library.
All headers should be able to compile on their own and not rely on the source file including something earlier. This can be easily detected by all source files always including their own header first.
In source files, include what you need (usually you can't get away with forward declarations in source files).
Also note to never use using in headers because it will pollute the global namespace.
If this seems like a lot of work, unfortunately that's because it is. This is a system inherited from C and requires some level of programmer maintenance. If you want to be able to decide at a high level what's used by your project and let the compiler/runtime figure it out, perhaps C++ isn't the right language for your project.

c++ include redeclaration

I have two libraries in my include path:
/usr/local/include/lib1/
/user/include/lib2/
Both define a header file "vec.h" and I get the following error:
/usr/local/include/lib1/vec.h:22: error: redeclared with...
How to handle this?
You do:
#include "lib1/vec.h"
#include "lib2/vec.h"
Your makefile should then have include paths up to the lib1 and lib2.
-I /usr/local/include /user/include
You should ensure that the headers have guards around them to make sure they don't get declared twice. You should see something like:
#ifndef MYHEADER_H_ab2592zx1__
#define MYHEADER_H_ab2592zx1__
#include ...
#include ...
class ...
#endif
You should have these guards regardless of whether you have two includes of the same name and they should typically end with something fairly random in order to limit/lower the possibility that they conflict with a header guard in another file.
(Sorry, can't comment yet, so posting as an answer.) What exactly is at line 22 of lib1/vec.h and what is the complete error message? It looks like the header is trying to declare something that was already declared in a different way somewhere, which may even have nothing to do with lib2/vec.h.
EDIT
So you have a name clash. I don't know what library trimesh2/include/Vec.h belongs to (probably lib2), but the problem is definitely a conflict between this header and lib1/img.h. Two libraries define two different classes with the same name Vec. There is no solution to this problem unless you have sources of one of the libraries and are willing to rename one of Vecs to something else and recompile it. You just can't have two different things with the same name in one program.

Circularly declaring Preprocessor directives? Or defines before includes?

I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:
main.h
#include "other.h"
#define MAX_GROUPS 100
struct Cat
{
int something[MAX_GROUPS];
}
In other.h I also need to use MAX_GROUPS, so do I also define MAX_GROUPS in other.h like this:
other.h
#define MAX_GROUPS 100
struct Other
{
int taco[MAX_GROUPS];
}
The problem is that I'm defining a constant more than one place. I want to keep it all together.
Alternatively, do I reinclude main.h?
other.h
#include "main.h"
struct Other
{
int taco[MAX_GROUPS];
}
The problem here I think its that is creates like a circular dependancy thing. main.h includes other.h which includes main.h which includes other.h which includes etc...
What is the best way to setup the defines and includes for a project so that things sorta cascade down to other included files? Is it common practice to simply do all your defines before your includes?
Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.
To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems with multiple definitions, use include guards:
#ifndef HEADER_THING_H
#define HEADER_THING_H
/* Rest of the header file goes here. */
#endif
That way if it is already included, it is harmless.
Because main.h #includes other.h, it doesn't need to #define MAX_GROUPS again. It'll pick up that definition from the inclusion.
Generally, you should put the defines inside whichever header is relevant -- or where it is primarily used. In this case, you should put MAX_GROUPS inside other.h. By including other.h in main.h, the define will also be picked up (as mentioned by jwismar).
For bigger projects, however, you'd be better off creating a header file containing only your manifest constants (defines) and just include that where needed.
You could also protect your constants against redefinition case by case...
#ifndef MAX_GROUPS
#define MAX_GROUPS 100
#endif

Can someone help clarify how header files work?

I've been working with C++ for a good couple of weeks now, but the mechanism behind header files (or the linker I suppose?) confuses the heck out of me. I've gotten in the habit of creating a "main.h" to group my other header files and keep the main.cpp tidy, but sometimes those header files complain about not being able to find a different header file (even though it's declared in the "main.h"). I'm probably not explaining it very well so here's an abridged version of what I'm trying to do:
//main.cpp
#include "main.h"
int main() {
return 0;
}
-
//main.h
#include "player.h"
#include "health.h"
#include "custvector.h"
-
//player.h
#include "main.h"
class Player {
private:
Vector playerPos;
public:
Health playerHealth;
};
-
//custvector.h
struct Vector {
int X;
int Y;
int Z;
};
-
//health.h
class Health {
private:
int curHealth;
int maxHealth;
public:
int getHealth() const;
void setHealth(int inH);
void modHealth(int inHM);
};
I won't include health.cpp because it's a bit lengthy (but does work), it does have #include "health.h".
Anyways, the compiler (Code::Blocks) complains that "player.h" can't find the types 'Health' or 'Vector'. I thought that if I used #include "main.h" into "player.h" it would be able to find the definitions for Health and Vector sense they're included in "main.h". I figured they would they would sort of tunnel their way though (player.h -> main.h -> health.h). But that didn't work too well. Is there some kind of a diagram or video that could clarify how this should be set up? Google wasn't much help (nor my book).
The best way to think of your header files are as an "automated copy-and-paste".
A good way to think about it (although not how this is actually implemented) is that when you compile a C file or C++ file, the preprocessor runs first. Every time it encounters an #include statement, it will actually paste the content of that file instead of the #include statement. This is done until there are no more includes. The final buffer is passed to the compiler.
This introduces several complexities:
First, if A.H includes B.H and B.H includes A.h, you've got a problem. Because every time you want to paste A, you would need B and it would internally have A ! That's a recursion. For this reason, header files use #ifndef, to ensure that the same part is not read multiple times. This is likely happening in your code.
Second, your C compiler reads the file after all the header files have been "flattened", so you need to consider that when reasoning about what is declared before what.
The other answers here have effectively explained the way header files and the preprocessor work. The biggest problem you have is the circular dependencies, which from experience, I know can be a royal pain. Also, when that starts happening, the compiler starts to behave in very odd ways and throw error messages that aren't super helpful. The method I was taught by a C++ guru in college was to start each file (a header file for instance) with
//very beginning of the file
#ifndef HEADER_FILE_H //use a name that is unique though!!
#define HEADER_FILE_H
...
//code goes here
...
#endif
//very end of the file
This uses preprocessor directives to automatically prevent circular dependencies. Basically, I always use an all uppercase version of the file name. custom-vector.h becomes
#ifndef CUSTOM_VECTOR_H
#define CUSTOM_VECTOR_H
This allows you to include files willie-nillie without creating circular dependencies because if a file is included multiple times, its preprocessor variable is already defined, so the preprocessor skips the file. It also makes it easier later on to work with the code because you don't have to sift through your old header files to make sure you haven't already included something. I'll repeat again though, make sure the variable names you use in your #define statements are unique for you otherwise you could run into problems where something doesn't get included properly ;-).
Good luck!
You have a circular dependency. Player includes main.h, but main.h includes player.h. Resolve this by removing one dependency or the other.\
Player.h should include health.h and custvector.h, and at this point, I don't think main.h needs any includes. Eventually it may need player.h.
includes work very simple, they just command preprocessor to add the contents of the file to where include is set. basic idea is to include headers that you depend on. in player.h you should include custvector.h and Health.h. In main only player.h, because all needed includes will be carried with player. and you don't need to include main.h in player.h at all.
it is good also to make sure that header is included only once. in this question general solution is given How to prevent multiple definitions in C? in case of Visual Studio you can use #pragma once, if Borland c++ there is also a trick but i forgot it.
You want to organize your #includes (and libraries, for that matter) in a DAG (directed, acyclic graph). That's the complicated way of saying "avoid cycles between header files":
If B includes A, A should not include B.
So, using "one big master main.h" is not the right approach, because it's hard to #include only direct dependencies.
Each .cpp file should include its own .h file. That .h file should only include things that it itself requires to compile.
There is usually no main.h, because main.cpp nobody needs the definition of main.
Furthermore, you'll want include guards to protect you against multiple includes.
For example
//player.h
#ifndef PLAYER_H_
#define PLAYER_H_
#include "vector.h" // Because we use Vector
#include "health.h" // Because we use Health
class Player {
private:
Vector playerPos;
public:
Health playerHealth;
};
#endif
-
//vector.h
#ifndef VECTOR_H_
#define VECTOR_H_
struct Vector {
int X;
int Y;
int Z;
};
#endif
-
//health.h
#ifndef HEALTH_H_
#define HEALTH_H_
class Health {
private:
int curHealth;
int maxHealth;
public:
int getHealth() const;
void setHealth(int inH);
void modHealth(int inHM);
};
#endif
The only time you want to aggregate a bunch of #includes into a single header is when you're providing it as a convenience for a very large library.
In your current example, you're going a little overboard - each class doesn't need its own header file. It can all go in main.cpp.
The c preprocessor literally inserts the file from a #include into the file that includes it (unless it has already been inserted, which is why you need the include guards). It allows you to use the classes defined in those files because you now have access to their definition.

One file doesn't recognize other file's class in C++

I have my own class inside the file "Particles.h" and the class's implementation is inside "Particles.cpp"
I want the file "Load.h" to recognize my classes inside there, so I've added the line
#include "Particles.h"
and the file doesn't recognize it and in the past everything was OK (I haven't made any changes inside that class).
What should I do?
It sounds like your include path - the list of directories that the compiler scans in order to locate files that you #include - is set incorrectly. Which compiler are you using?
Well, if you listed your error codes, it might help. Off the top of my head, do you have something in Particles.h to make sure that the file is only included once? There are two methods of doing this. The first is to use #pragma once, but I think that might be Microsoft specific. The second is to use a #define.
Example:
#ifndef PARTICLES_H
#define PARTICLES_H
class CParticleWrapper
{
...
};
#endif
Also, unless you're deriving from a class in Particles.h or using an instance of a class instead of a pointer, you can use a forward declaration of the class and skip including the header file in a header file, which will save you compile time.
#ifndef LOAD_H
#define LOAD_H
class CParticleWrapper;
class CLoader
{
CParticleWrapper * m_pParticle;
public:
CLoader(CParticleWrapper * pParticle);
...
};
#endif
Then, in the Load.cpp, you would include the particle.h file.
make sure the file "Particles.cpp" has also included "Particles.h" to start with and the files are in the same folder and they are all part of the same project. it will help if you also share the error message that you are getting from your compiler.
Dev C++,It uses GCC,
The line is:
Stone *stone[48];
and it says: "expected constructor, destructor, or type conversion before '*' token ".
It sounds like you need to include the definition of the Stone class, but it would be impossible to say without more details. Can you narrow down the error by removing unrelated code and post that?