Prevent including a header file twice.

How can I prevent a header file from being included twice. Are there some kind of header guards you can put on top of your file and what is the syntax?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Yes and No.

The standard, portable way to do this is by putting something like..

    #ifndef _MYHEADER_H
    #define _MYHEADER_H

    [... header body ...]


This will achieve, in effect, what you want.  Of course, the most compilers will still read the file.  They'll just ignore everything the second time.

Some compilers (GCC, for example) notice this structure and actually don't read the file the second time an long as all the body of the header file is between the ifndef/endif pair.

Other compilers support something like

    #pragma once

to be included in the file (along with the above standard) to say that this file should never be read more than once.  It's basically just a hint for the compiler.  Check your compiler manual for more information about supported pragmas.

Objective-C has an "#import" directive that functions like "#include" except that it will only include a given file once.  This is generally frowned upon since it should be up to the author of the header file to decide if it should be included more than once, not the job of the person writing the program that uses that header file.

So, the bottom line...  Use the "#ifndef" bit always (for portability).  Add the "#pragma" thing if you want.

-- Brian

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.