Show: Delphi C++
Display Preferences

#pragma once

From RAD Studio XE3
Jump to: navigation, search

Go Up to Pragma Directives Overview Index

Syntax (See Pseudo-grammar)

#pragma once

Description

#pragma once is a preprocessor directive used to prevent header files from being included multiple times. The #pragma once directive, once present in a file, assures that the file will not be included multiple times in the current project.

Example

An example of why #pragma once is useful is the fact that a file that includes another header is sufficient. For a logical example where the directive can be used, see the code below.

Vertex.h

#pragma once
struct Vertex{
  int x_coord;
  int y_coord;
  int z_coord;
};

Triangle.h

#include "Vertex.h"
struct Triangle{
  Vertex p1;
  Vertex p2;
  Vertex p3;
};

Square.h

struct Square{
  Vertex v1;
  Vertex v2;
  Vertex v3;
  Vertex v4;
};

Drawing.cpp

#include <vcl.h>
#include "Triangle.h"
#include "Vertex.h"
int main()
{
  //a triangle
  Triangle tr0;
  //a square
  Square sq0;
  return 0;
}

Because both the triangle and the square need the vertex struct to know their position in three-dimensional space, both of them include Vertex.h. The triangle and the square are included too in the main .cpp, therefore the Vertex.h file would be included twice (by Triangle.h and by Square.h). Using #pragma once in Vertex.h prevents the preprocessor from including the file a second time. As a result, no error is thrown.

Note: The same thing can be achieved with #ifndef/#define/#endif, which is the ANSI standard way of dealing with the double inclusion problem.
Personal tools
Previous Versions
In other languages