0

I have a confusion with the way #include directives work in C/C++. My first question is:

If header A includes header B first and then header C, is everything defined in header B immediately available in header C ? e.g:

/* FILE: header A */

#include "B.h"
#include "C.h" //are stuff from B.h available INSIDE C.h now?

My second question is (somewhat related to above) is this inclusion behavior different in C and C++?

Lastly, I am trying to compile freeglut with a C++ compiler and freeglut's header has the following:

#ifndef  __FREEGLUT_H__
#define  __FREEGLUT_H__

#include "freeglut_std.h"
#include "freeglut_ext.h"

#endif /* __FREEGLUT_H__ */

Problem is that, under compilation as C, everything is fine but switching to C++ in Visual Studio suddenly makes freeglut_ext.h to be unaware of everything defined in freeglut_std.h. Is this an issue limited to MSVC?

Sepehr
  • 2,051
  • 19
  • 29

2 Answers2

2

#include in both C and C++ is pure textual inclusion, so yes to your first question and no to your second one. I don't know freeglut so I can't tell what #ifdef __cplusplus (or other) games its headers may be playing -- not knowing what error messages you're getting to convince you that the second file is "unaware" of the first makes it unfeasible to help with your stated problem, though the answers to your stated questions are easy:-)

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • hmmm, you brought up a good point, it does include `extern C` on top of its headers. The errors are simply `#define` tokens in `"freeglut_std.h"` not available in `"freeglut_ext.h"`. Errors like: `GL\freeglut_ext.h(130): error C2144: syntax error : 'void' should be preceded by ';'` – Sepehr Dec 20 '14 at 03:57
0

This is just an answer to the first part of your question.

C++ compilation happens with each .cpp file being compiled separately. Headers separately are not part of the compilation process unless you explicitly include them into a .cpp file. #include directive basically copies all the contents of the header into the .cpp in which it has been included. So there is no question of something defined in one header being available in another header.

But in your case, if there are names defined in B.h which are referred in C.h then inclusion order has to be B.h first and then C.h

Arun
  • 3,138
  • 4
  • 30
  • 41
  • But it was supposed to last for one single unit of compilation as far as I can read here and there online, how come the C compilation passes? – Sepehr Dec 20 '14 at 03:55