What does #pragma once mean in C? [duplicate]

It’s used to replace the following preprocessor code:

#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

A good convention is adding both to support legacy compilers (which is rare though):

#pragma once
#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

So if #pragma once fails the old method will still work.

2023 update

I see some people in the comment section advocate for using guards instead of #pragma once.
This makes little to no sense in 2023 and beyond unless you are targeting some special compiler that you know does not support #pragma once.

Today’s best practice is to use only #pragma once and don’t bother with guards at all. Reasons being

  1. All major compilers been supporting this forever and that is not
    going to change.
  2. Using #pragma allows the compiler to use its internal caches which is of course faster than using the pre-processor which will always include the contents of your file just to later stumble on your guards and dismiss the whole thing.
  3. It’s a lot shorter and easier to add/maintain

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)