-2

If I have two files like below

//file1.h
#include "file2.h"
//file2.h
#include "file1.h"

This kind of loop dependency can occur with more than two files, just for the sake of simplicity I listed only two. What happens in this kind of situation? I am also interested to know if the C++ standard restricts this kind of situation to happen.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
pasha
  • 1,987
  • 18
  • 32

1 Answers1

4

The standard does not restrict such recursion. Common practice to avoid it is to use

include-guards

#ifndef FILE_H
#define FILE_H

// content of the header file

#endif

or #pragma once:

#pragma once

// content of the header file

Please note that #pragma one, although supported by many compilers, is not a part of the standard:

#pragma once is a non-standard but widely supported preprocessor directive

AlexD
  • 31,231
  • 3
  • 67
  • 62
  • It should be mentioned that #pragma once is not standard C++ (or C) whereas header guards are standard. See http://stackoverflow.com/a/787539/5226168. – Anders Dec 27 '15 at 20:12
  • @Anders Makes sense. Included. – AlexD Dec 27 '15 at 20:15