0

The question is asked because in some situation the include order really matters. For example, as said on LearnOpenGL or the GLFW doc, glad.h must be included before glfw3.h.

For including headers, I have been following the rule that each file should only include its necessary headers explicitly, and headers should all have include guards.

Thus the problem comes. In a project, some files only need glfw3.h and some only need glad.h. Then when compiling, how to guarantee the compiler always reads glad.h before glfw3.h?

Two solutions I can think of are:

  1. manually arrange the order of source files when feeding them to the compiler.
  2. write a new header file called glad_glfw.h which contains the two headers in the right order. Then any other files which need to include any of the two include the glad_glfw.h.

I think 1. would eventually be difficult when the project grows large, and 2. kind of violates the rule of minimum include. So I want to ask if there are any better ways to do this?

BDL
  • 18,169
  • 14
  • 45
  • 47
Chen
  • 83
  • 5
  • This must be enforced by the header files themselves. There are a number of ways to enforce this, but header files must be changed to do that. You can't enforce this outside of the header files, except as according to your 2nd solution. – Sam Varshavchik Sep 15 '19 at 12:53
  • Thanks for the quick answer. You mean I have to change the library headers? – Chen Sep 15 '19 at 13:00
  • 1
    Yes. One header file `#define`s a preprocessor symbol. The second header file reports an `#error` if the symbol is `#ifdef`ed. This is the right way to do it. You can't do anything if the library header files do not enforce correct usage. – Sam Varshavchik Sep 15 '19 at 13:03
  • I don't see how 2 violates rule of minimum include. – user7860670 Sep 15 '19 at 13:23
  • If you own the header files, you can instrument them so that they `#error` if not included in the right order, by using header guards and checks. If you do not own the header files (i.e., you can't modify them), you can make shim header files that include the real header files in the right order, and only use your shim header files in your code. – Eljay Sep 15 '19 at 15:45

2 Answers2

0

I typically use #pragma once as an include guard.

A little less prone to programmer error than #ifdef's, but it is a little non-standard.

https://en.wikipedia.org/wiki/Pragma_once

James
  • 93
  • 9
0

Yet another option - "option 3," perhaps - would be to include those header files in a "precompiled header." This is especially useful if you expect the header files themselves to rarely, if ever, change.

BTownTKD
  • 7,359
  • 2
  • 25
  • 43