Reputation: 43
I’ve studied C, and now I’ve decided to switch to C++.
So, in C, I used #ifndef
#endif
in my header files. Should I use the same commands in C++? Or are there some alternatives?
Upvotes: 1
Views: 242
Reputation: 661
Besides macro guard explained by others, it would be nice to have a namespace and then your classes, structs, and all other functions go inside this namespace.
Upvotes: 0
Reputation: 776
The answer from Commader_Quazar is right and enough.
ALternatively you can substitute:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations (and certain types of definitions) here
#endif
with:
#pragma once
// your declarations (and certain types of definitions) here
which lets you write 1 line of code instead of 3, and is less error prone (since in this case you don't have to worry about remembering to put #endif
at the end of the file) however I personally prefer the first option.
Upvotes: 0
Reputation: 1
The file/header relationship is identical in C and C++.
foo.h:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations (and certain types of definitions) here
#endif
The C++ preprocessor is essential the same when compared to it’s C counterpart. All directives will work in either language whether written in a header (.h) or a source file (.c, .cc, .cpp).
Read more about the wonders of headers here!
Upvotes: 0
Reputation: 36516
Yes, the preprocessor works (mostly) the same way, so you should still use preprocessor directives to guard against including the same code more than once.
Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
Upvotes: 4