Home > Software engineering >  Question about #include in header files (c )
Question about #include in header files (c )

Time:10-13

so I've been experiencing some strange issues with using #include in header files. The goal is to make so any custom or common systems are all in one place that I can just include in whatever file I'm working on. This has been working so far, but I noticed recently that seemingly for no reason a new header file I add to it won't have access to any code that was included before it like the rest have. It's set up a bit like this:

// includes.h
#include <cstdlib>
#include <iostream>
#include <vector>
#include <map>
#include <random>
#include <cmath>
#include <memory>
#include "a.h"
#include "b.h"
#include "c.h"

Now what's happening is a.h and b.h can use all code from the includes from above them, and b.h can use code from a.h, but seemingly for no reason, c.h cannot use any code from anything included above it, but occasionally making an entirely new header file with a different name will work. I'm unaware as to what could be causing this issue, and would love help understanding this problem. If any more clarification should be provided please let me know.

CodePudding user response:

Each header should include what they use. It should not be depended on the user to include.

For example: C uses B, and B uses A

  • c.h: #include B.h
  • b.h: #include A.h

Also don't forget to add #pragma once to the headers. this will result that that header file will only be loaded once. For example: if you would have a class D, which includes A.h. It will be only loaded once even though B and D both use A.h.

See also: https://www.incredibuild.com/blog/include-what-you-use-how-to-best-utilize-this-tool-and-avoid-common-issues

https://www.fluentcpp.com/2021/01/01/include-what-you-use/

https://include-what-you-use.org/

CodePudding user response:

I am not exactly sure. One simple thing you might miss is ensuring each header is included only once. Most likely, you are missing that on the "a.h" or "b.h" file. You should do that in every header file to avoid cyclic dependencies, including "c.h.". You can do that by

#pragma once

or

#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif

See: Why are #ifndef and #define used in C header files? https://learn.microsoft.com/en-us/cpp/preprocessor/once?view=msvc-170

  •  Tags:  
  • c
  • Related