Reputation: 97
I've searched all over for some clarification on what #pragma once actually does and can't find definitive answers for some questions I still have.
Does #pragma once insure that the header file it is included in is only called once AS WELL AS that the headers which are included in said header file are not yet included? Also, if it is only called once, does that mean a .cpp file that needs a particular header will not be able to access it? If a header file is marked with #pragma once and included in a .cpp, can that header file be used again elsewhere?
These are the sorts of clarifications I am not finding. Sorry if there is documentation that clarifies this somewhere, but I really couldn't find any thing specific enough.
Upvotes: 7
Views: 9270
Reputation: 7960
Does #pragma once insure that the header file it is included in is only called once AS WELL AS that the headers which are included in said header file are not yet included?
The pragma doesn't affect other headers. if the header with the pragma 'a.h' includes 'b.h', 'b.h' can be included again via a third header or directly.
Also, if it is only called once, does that mean a .cpp file that needs a particular header will not be able to access it?
You can include the header from anywhere you want, as many times as you see fit.
If a header file is marked with #pragma once and included in a .cpp, can that header file be used again elsewhere?
Yes, this is the normal practice with headers.
Where's the catch?
If you really need to include the headers more than once and every include performs a different operation than don't use pragma once or a sentry macro. These cases are not common.
A benefit to pragma once
is that it saves you from bugs like having 2 header files that by chance have the same sentry macro. this can happen when 2 header files have the same file name and same coding style for macro names.
Upvotes: 3
Reputation: 137810
#pragma once
only guards a single file in a single translation unit, not counting its sub-hierarchy of inclusion. (However, if the file's second inclusion is prevented, it doesn't have an opportunity to doubly-include anything else.)
You can still include it again from another .cpp
.
The file is usually identified by its inode number.
Note that #pragma once
is strictly nonstandard, and most still prefer traditional #ifndef
header guards.
Upvotes: 10
Reputation: 3397
#pragma once
causes the current source file to be included only once in a single compilation.
It's essentially similar to #include
guards.
Upvotes: 5