#prama once --vs-- #define
The objective here is to be able to tell when a certain file is included.
For example, suppose we have a header file named MyClass.h. In Main.cpp, we want to check if MyClass.h is included, and if not... post an error.
If we use the C-Style #define approach, you do the following in MyClass.h:
Code:
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
// All code here
#endif
Now, in Main.cpp, you simply check if the file is included by doing the following:
Code:
#ifndef _MYCLASS_H_
// post error to output window, forgot the exact command at the moment
Now if we use the C++ style, which is via the #pragma directive, I have no idea how you would be able to tell if a file was included or not.
In MyClass.h:
In Main.cpp:
Any help? Thanks...
Re: #prama once --vs-- #define
#pragma is not "the C++ style". Pragmas, by definition, are compiler-dependent. There is no guarantee that all compilers will support #pragma once, or that they will use the same form of the statement, even if they have an equivalent.
The #define latch is the only portable way of ensuring that headers are only included once.
Re: #prama once --vs-- #define
My mistake, I thought it was a new feature of C++.
In any case, what is the recommended method?
Re: #prama once --vs-- #define
The #define system that you've already outlined
Re: #prama once --vs-- #define
I saw the results of an experiment that someone did that showed that #pragma once resulted in faster compile times than #define. The experiment involved about 200 trivial files that each included all of the other files. Pragma once was significantly faster than the #define method; however, if you have actual code in those files, I don't think it'll make much of a difference overall : )
You could try using both of them if you don't mind using a compiler-specific bit of code -- that's what I've been doing for something I'm working on at home, and it works in MSVC++.net in windows and GCC in linux.
As for your original question, I haven't a clue, sorry : ). I don't think it's possible to tell that when using #pragma once (it might be possible, but I wouldn't bet on it).
Re: #prama once --vs-- #define
Quote:
Originally Posted by smozoma
I saw the results of an experiment that someone did that showed that #pragma once resulted in faster compile times than #define.
Which makes sense if you think about it: when the preprocessor encounters an #ifndef directive, it still has to scan through the rest of the file to determine where the corresponding #endif falls, whereas processing of that header can stop immediately (I think) once a #pragma once is encountered. This is probably why VC++ generates header files that use both types of guards (with the #pragma enclosed in an #if...#endif block to avoid unwanted effects if the headers are used with a non-VC++ compiler).