Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m reading through a PDF on C++ programming from this page on Stanford\'s site

ID: 654667 • Letter: I

Question

I'm reading through a PDF on C++ programming from this page on Stanford's site. It says that when you're creating a C++ header file for a library interface, use a #ifndef preprocessor command to make sure you don't compile the same interface twice.

So, your header would look something like this:

/**
MyFile.h
*/

#ifndef _MyFile_h
#define _MyFile_h

// Function prototypes

#endif
But, I've always heard people say that using preprocessor commands like #define is (or quickly leads to) bad coding practice. I'm just starting to learn C++, so I don't want to get something ingrained that is bad.

Question: Is it "proper" coding style to use preprocessor commands as above?

Explanation / Answer

This is one of the few uses of C++ macros that is widely accepted. It is usually called an include guard. As an alternative, most modern compilers support #pragma once. This is much cleaner, but slightly less portable.