[C++]Tangled in headers, etc.
I've been trying to organize my code by sticking it in separate header files. It's been going well except for one thing;
For example, let's say I have "main.cpp", "a.h", "a.cpp", "b.h", "b.cpp".
main.cpp;
PHP Code:
#include "stdio"
#include "a.h"
#include "b.h"
int main()
{
//etc
}
a.h:
PHP Code:
#include "stdio"
#include "b.h"
class A
{
B someThing;
//stuff
};
b.h:
PHP Code:
#include "stdio"
#include "a.h"
class B
{
A anotherThing;
//stuff
};
main.cpp -> a.h (-> b.h) + b.h (-> a.h)
^That situation will already result in a "class already defined" error.
Re: [C++]Tangled in headers, etc.
The preprocessor inclusion just replaces the inclusion statement with the whole content of the file you're including. The solution is using a forward declaration such as...
PHP Code:
class B;
class A
{
B b;
// ...
}
Useful resources: 1, 2, 3 (first answer is great).
Re: [C++]Tangled in headers, etc.
just put a #pragma once at the top of each *.h file
#pragma once
...It's a short way of saying "only include me once"
If you're using some crappy compiler that doesn't support #pragma once, then you wrap it with #ifndef, #define, #endif. Same effect as #pragma once. Just a lot more typing and room for conflicts (Use a different #define value for each .h file. Don't use __HEADER_A_H each time :P)
#ifndef __HEADER_A_H
#define __HEADER_A_H 0
..the rest of your a.h file
#endif
---------- Post added at 03:10 AM ---------- Previous post was at 03:08 AM ----------
...And consider using pointers in the declarations if your references are truly circular. You can do
ClassA *a;
if you get an error doing just:
ClassA a;
In the constructor, call a=new ClassA(); and destructor calls "delete a;"
Re: [C++]Tangled in headers, etc.
Thanks for the help! I use MSVC 10 and IIRC it does support #pragma once.
Also Zeillinger thanks for those links :)