Code::Blocks Forums
User forums => General (but related to Code::Blocks) => Topic started by: Deamon on April 03, 2006, 07:12:36 am
-
Hi forum,
i made a small test app along my c++ study and found an odd circumstance. I made a console project that contains three files with the following test code.
-------------------------------------------------
//main.cpp
#include <iostream>
#include "includestd.h"
#ifndef _process_h
#include "process.h"
#endif
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
--------------------------------------------------
// process.h
class vehicle{int i;};
--------------------------------------------------
// includestd.h
#ifndef _process_h
#include "process.h"
#endif
--------------------------------------------------
When i try to compile this i get this errors:
process.h:4: redefinition of `class vehicle'
process.h:4: previous definition of `class vehicle'
Obviously this is becose of an double inclusion of the process.h, but why ?
I have included this code in to the main.cpp to prevent a double inclusion but it still includes it double:
#ifndef _process_h
#include "process.h"
#endif
Do i have a misconception here ?
BTW: When i change the process.h code to:
-------------------------
#ifndef _process_h
#define _process_h
class vehicle{int i;};
#endif
-------------------------
it works fine but shouldn't it work even without it ?
regards,
Deamon
-
The "standard" way to avoid multiple includes is the 2nd way (that you also confirmed that it works).
Why the other way doesn't work? You never define _process_h!
-
Why the other way doesn't work? You never define _process_h!
That means the first method is pointless ? That means that if i have defined the .h then i can include it where ever i want it without fear of an double inclusion in the for of #include "process.h" ?
I don't need to check it via:
#ifndef _process_h
#include "process.h"
#endif
???
But is there a way to check if a .h was already included and include it only if it's not ?
some sort of:
#ifninc _process_h
#include "process.h"
#endif
???
regards,
Deamon
-
Remember, #ifndef / #define / #endif is just a fancy (ab)use of the preprocessor for preventing multiple inclusion; it's not magical in any way.
#ifndef _process_h -- IF "_process_h" has not already been defined
#define _process_h -- then define it now
... (code) ... -- and process the following code
#endif -- (otherwise the intervening code is skipped over, because _process_h was already defined)
If you don't include the line "#define _process_h", then obviously it will always process the code between the #ifndef / #endif, because _process_h is never #defined.
Use "#ifdef" to check if a macro HAS been defined (note the lack of an 'n'). #ifdef and #ifndef are shortened forms of "#if defined" and "#if !defined".
-
Ok i think i got it now. Thank you :)