user147502
user147502

Reputation: 1118

What is #pragma once used for?

I have found the following code when refactoring:

#ifndef TARGET_OS_LINUX
#pragma once
#endif

Can anyone help me understand #pragma once?

What, when, where, and why is it used? Do you have an example?

Upvotes: 46

Views: 13744

Answers (3)

Gabriel Staples
Gabriel Staples

Reputation: 53205

GCC's official documentation states: https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html:

#pragma once

If #pragma once is seen when scanning a header file, that file will never be read again, no matter what. It is a less-portable alternative to using #ifndef to guard the contents of header files against multiple inclusions.

See also my answer here: #ifndef syntax for include guards in C++.

Upvotes: 0

John Calsbeek
John Calsbeek

Reputation: 36547

#pragma is just the prefix for a compiler-specific feature.

In this case, #pragma once means that this header file will only ever be included once in a specific destination file. It removes the need for include guards.

Upvotes: 51

f0b0s
f0b0s

Reputation: 3097

  • What -- it is header guard. This file will be included only once.
  • When -- at a compile process
  • why -- to avoid double including.

"Header guards are little pieces of code that protect the contents of a header file from being included more than once."

Upvotes: 18

Related Questions