xxx
xxx

Reputation: 43

What should a header file look like for C++ projects?

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

Answers (4)

Iman Abdollahzadeh
Iman Abdollahzadeh

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

Gianluca Bianco
Gianluca Bianco

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

Commader_Quazar
Commader_Quazar

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

Chris
Chris

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

Related Questions