#include files in different files












3















If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?




If there are no header guards, what will happen?











share|improve this question

























  • If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

    – BCS
    Dec 28 '09 at 0:51
















3















If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?




If there are no header guards, what will happen?











share|improve this question

























  • If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

    – BCS
    Dec 28 '09 at 0:51














3












3








3








If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?




If there are no header guards, what will happen?











share|improve this question
















If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?




If there are no header guards, what will happen?








c compiler-construction






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 3:48









Jonathan Leffler

567k916781030




567k916781030










asked Dec 27 '09 at 14:32









VijayVijay

32.6k75187296




32.6k75187296













  • If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

    – BCS
    Dec 28 '09 at 0:51



















  • If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

    – BCS
    Dec 28 '09 at 0:51

















If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

– BCS
Dec 28 '09 at 0:51





If you wrote the file without guards, add them. If someone else wore the file without guards (e.g. a library) dump it and find another library as they don't known what they are doing.

– BCS
Dec 28 '09 at 0:51












7 Answers
7






active

oldest

votes


















3














Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:



int printf(const char*, ...);
int printf(const char*, ...);


is perfectly legal and has a small compilation overhead but no runtime overhead.



That's what happens when an unguarded include file is included more than once.



Note that it is not true for everything in an include file. You can't redeclare an enum, for example.






share|improve this answer































    7














    Most C headers include are wrapped as follows:



    #ifndef FOO_H
    #define FOO_H

    /* Header contents here */

    #endif


    The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.



    There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:



    #ifndef FOO_H
    #include <foo.h>
    #endif


    This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).






    share|improve this answer
























    • BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

      – BCS
      Dec 28 '09 at 23:05











    • Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

      – mrkj
      Dec 29 '09 at 13:19











    • Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

      – John Bollinger
      Nov 22 '18 at 4:34



















    5














    This is usually solved with preprocessor statements:



    #ifndef __STDLIB_H
    #include <stdlib.h>
    #define __STDLIB_H
    #endif


    Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.






    share|improve this answer
























    • Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

      – Vijay
      Dec 27 '09 at 14:36






    • 3





      The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

      – jcoder
      Dec 27 '09 at 14:41






    • 1





      If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

      – BCS
      Dec 28 '09 at 23:10



















    5














    The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.



    Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.



    Response to edit:



    Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.



    Similarly, it is your responsibility to use header guards on your own headers.



    If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.






    share|improve this answer


























    • Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

      – Richard Pennington
      Dec 27 '09 at 14:37











    • This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

      – jcoder
      Dec 27 '09 at 14:40











    • @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

      – Drew Dormann
      Dec 27 '09 at 14:45











    • "variety of errors" Heh.

      – Chad Okere
      Dec 27 '09 at 15:03



















    2














    This is done by one of the two popular techniques, both of which are under stdlib's responsibility.



    One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.



    Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)



    You must also do the same in all header files you produce. Or, headers that include yours will have a problem.






    share|improve this answer
























    • I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

      – jcoder
      Dec 27 '09 at 14:42






    • 1





      @JB: The CPP man page (gcc's pre-processor) says it does that.

      – BCS
      Dec 28 '09 at 23:11



















    2














    As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.



    Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration



    Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.



    Also, always utilize the include guards or #pragma once for your own header files!






    share|improve this answer



















    • 1





      I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

      – Alok Singhal
      Dec 27 '09 at 15:02



















    1














    As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:




    Standard headers may be included in any order; each may be included more than once in
    a given scope, with no effect different from being included only once, except that the
    effect of including <assert.h> depends on the definition of NDEBUG.




    How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".



    But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.



    For example, given a header:



    int a;


    including it twice will result in two definitions of a. This is a Bad Thing.



    The easiest way to avoid conflict like this is to use include guards as defined above:



    #ifndef H_HEADER_NAME_
    #define H_HEADER_NAME_
    /* header contents */
    #endif


    This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)



    Of course, in your code, you should ensure that the macro name for include guard satisfies this:




    • It doesn't start with E followed by an uppercase character,

    • It doesn't start with PRI followed by a lowercase character or X,

    • It doesn't start with LC_ followed by an uppercase character,

    • It doesn't start with SIG/SIG_ followed by an uppercase character,


    ..etc. (That is why I prefer the form H_NAME_.)



    As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).



    #ifndef SZ
    #define SZ 1024
    #else
    #if SZ == 1024
    #undef SZ
    #define SZ 128
    #else
    #error "You can include me no more than two times!"
    #endif
    #endif





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1966075%2finclude-files-in-different-files%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      7 Answers
      7






      active

      oldest

      votes








      7 Answers
      7






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:



      int printf(const char*, ...);
      int printf(const char*, ...);


      is perfectly legal and has a small compilation overhead but no runtime overhead.



      That's what happens when an unguarded include file is included more than once.



      Note that it is not true for everything in an include file. You can't redeclare an enum, for example.






      share|improve this answer




























        3














        Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:



        int printf(const char*, ...);
        int printf(const char*, ...);


        is perfectly legal and has a small compilation overhead but no runtime overhead.



        That's what happens when an unguarded include file is included more than once.



        Note that it is not true for everything in an include file. You can't redeclare an enum, for example.






        share|improve this answer


























          3












          3








          3







          Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:



          int printf(const char*, ...);
          int printf(const char*, ...);


          is perfectly legal and has a small compilation overhead but no runtime overhead.



          That's what happens when an unguarded include file is included more than once.



          Note that it is not true for everything in an include file. You can't redeclare an enum, for example.






          share|improve this answer













          Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:



          int printf(const char*, ...);
          int printf(const char*, ...);


          is perfectly legal and has a small compilation overhead but no runtime overhead.



          That's what happens when an unguarded include file is included more than once.



          Note that it is not true for everything in an include file. You can't redeclare an enum, for example.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 27 '09 at 14:41









          Richard PenningtonRichard Pennington

          17.4k33462




          17.4k33462

























              7














              Most C headers include are wrapped as follows:



              #ifndef FOO_H
              #define FOO_H

              /* Header contents here */

              #endif


              The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.



              There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:



              #ifndef FOO_H
              #include <foo.h>
              #endif


              This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).






              share|improve this answer
























              • BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

                – BCS
                Dec 28 '09 at 23:05











              • Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

                – mrkj
                Dec 29 '09 at 13:19











              • Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

                – John Bollinger
                Nov 22 '18 at 4:34
















              7














              Most C headers include are wrapped as follows:



              #ifndef FOO_H
              #define FOO_H

              /* Header contents here */

              #endif


              The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.



              There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:



              #ifndef FOO_H
              #include <foo.h>
              #endif


              This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).






              share|improve this answer
























              • BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

                – BCS
                Dec 28 '09 at 23:05











              • Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

                – mrkj
                Dec 29 '09 at 13:19











              • Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

                – John Bollinger
                Nov 22 '18 at 4:34














              7












              7








              7







              Most C headers include are wrapped as follows:



              #ifndef FOO_H
              #define FOO_H

              /* Header contents here */

              #endif


              The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.



              There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:



              #ifndef FOO_H
              #include <foo.h>
              #endif


              This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).






              share|improve this answer













              Most C headers include are wrapped as follows:



              #ifndef FOO_H
              #define FOO_H

              /* Header contents here */

              #endif


              The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.



              There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:



              #ifndef FOO_H
              #include <foo.h>
              #endif


              This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 27 '09 at 14:37









              mrkjmrkj

              2,5501323




              2,5501323













              • BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

                – BCS
                Dec 28 '09 at 23:05











              • Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

                – mrkj
                Dec 29 '09 at 13:19











              • Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

                – John Bollinger
                Nov 22 '18 at 4:34



















              • BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

                – BCS
                Dec 28 '09 at 23:05











              • Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

                – mrkj
                Dec 29 '09 at 13:19











              • Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

                – John Bollinger
                Nov 22 '18 at 4:34

















              BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

              – BCS
              Dec 28 '09 at 23:05





              BTW, gcc has a special case optimization in it's pre-processor to make the second form redundant.

              – BCS
              Dec 28 '09 at 23:05













              Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

              – mrkj
              Dec 29 '09 at 13:19





              Thanks; for anybody else wanting to follow up on this, the reference is here: gcc.gnu.org/onlinedocs/cpp/…

              – mrkj
              Dec 29 '09 at 13:19













              Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

              – John Bollinger
              Nov 22 '18 at 4:34





              Whether system headers are wrapped with include guards is an implementation detail of no outward import. The language requires that multiple inclusion of standard library headers in the same scope have no different effect than single inclusion (with a minor caveat regarding assert.h). An implementation can conform to that requirement in any way it likes. That does not need to be multiple-inclusion guards, nor indeed any mechanism that can be used with other headers.

              – John Bollinger
              Nov 22 '18 at 4:34











              5














              This is usually solved with preprocessor statements:



              #ifndef __STDLIB_H
              #include <stdlib.h>
              #define __STDLIB_H
              #endif


              Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.






              share|improve this answer
























              • Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

                – Vijay
                Dec 27 '09 at 14:36






              • 3





                The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

                – jcoder
                Dec 27 '09 at 14:41






              • 1





                If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

                – BCS
                Dec 28 '09 at 23:10
















              5














              This is usually solved with preprocessor statements:



              #ifndef __STDLIB_H
              #include <stdlib.h>
              #define __STDLIB_H
              #endif


              Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.






              share|improve this answer
























              • Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

                – Vijay
                Dec 27 '09 at 14:36






              • 3





                The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

                – jcoder
                Dec 27 '09 at 14:41






              • 1





                If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

                – BCS
                Dec 28 '09 at 23:10














              5












              5








              5







              This is usually solved with preprocessor statements:



              #ifndef __STDLIB_H
              #include <stdlib.h>
              #define __STDLIB_H
              #endif


              Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.






              share|improve this answer













              This is usually solved with preprocessor statements:



              #ifndef __STDLIB_H
              #include <stdlib.h>
              #define __STDLIB_H
              #endif


              Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 27 '09 at 14:35









              schnaaderschnaader

              42.4k887122




              42.4k887122













              • Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

                – Vijay
                Dec 27 '09 at 14:36






              • 3





                The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

                – jcoder
                Dec 27 '09 at 14:41






              • 1





                If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

                – BCS
                Dec 28 '09 at 23:10



















              • Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

                – Vijay
                Dec 27 '09 at 14:36






              • 3





                The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

                – jcoder
                Dec 27 '09 at 14:41






              • 1





                If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

                – BCS
                Dec 28 '09 at 23:10

















              Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

              – Vijay
              Dec 27 '09 at 14:36





              Yes you are right! but if this is not implemented what would happen?how does the compiler handle?will it create any errors?

              – Vijay
              Dec 27 '09 at 14:36




              3




              3





              The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

              – jcoder
              Dec 27 '09 at 14:41





              The include guards are always inside the .h file. if they weren't there you'd get lots of duplicate definition errors

              – jcoder
              Dec 27 '09 at 14:41




              1




              1





              If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

              – BCS
              Dec 28 '09 at 23:10





              If someone else shipped a .h file without guards they are 1) incompetent or 2) doing something tricky and you would break it if you tried to "fix" it. (If #2, they are also possibly to clever for there own good.)

              – BCS
              Dec 28 '09 at 23:10











              5














              The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.



              Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.



              Response to edit:



              Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.



              Similarly, it is your responsibility to use header guards on your own headers.



              If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.






              share|improve this answer


























              • Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

                – Richard Pennington
                Dec 27 '09 at 14:37











              • This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

                – jcoder
                Dec 27 '09 at 14:40











              • @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

                – Drew Dormann
                Dec 27 '09 at 14:45











              • "variety of errors" Heh.

                – Chad Okere
                Dec 27 '09 at 15:03
















              5














              The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.



              Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.



              Response to edit:



              Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.



              Similarly, it is your responsibility to use header guards on your own headers.



              If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.






              share|improve this answer


























              • Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

                – Richard Pennington
                Dec 27 '09 at 14:37











              • This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

                – jcoder
                Dec 27 '09 at 14:40











              • @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

                – Drew Dormann
                Dec 27 '09 at 14:45











              • "variety of errors" Heh.

                – Chad Okere
                Dec 27 '09 at 15:03














              5












              5








              5







              The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.



              Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.



              Response to edit:



              Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.



              Similarly, it is your responsibility to use header guards on your own headers.



              If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.






              share|improve this answer















              The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.



              Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.



              Response to edit:



              Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.



              Similarly, it is your responsibility to use header guards on your own headers.



              If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 12:11









              Community

              11




              11










              answered Dec 27 '09 at 14:35









              Drew DormannDrew Dormann

              41.7k979142




              41.7k979142













              • Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

                – Richard Pennington
                Dec 27 '09 at 14:37











              • This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

                – jcoder
                Dec 27 '09 at 14:40











              • @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

                – Drew Dormann
                Dec 27 '09 at 14:45











              • "variety of errors" Heh.

                – Chad Okere
                Dec 27 '09 at 15:03



















              • Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

                – Richard Pennington
                Dec 27 '09 at 14:37











              • This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

                – jcoder
                Dec 27 '09 at 14:40











              • @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

                – Drew Dormann
                Dec 27 '09 at 14:45











              • "variety of errors" Heh.

                – Chad Okere
                Dec 27 '09 at 15:03

















              Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

              – Richard Pennington
              Dec 27 '09 at 14:37





              Where header guards are similar to schnaader's answer, but inside the stdlib.h header.

              – Richard Pennington
              Dec 27 '09 at 14:37













              This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

              – jcoder
              Dec 27 '09 at 14:40





              This is entirely correct, although I believe that many modern compilers recognise the header guards pattern the first time they include the file and know they don't need to open it again. That in no way changes how they work though it's just an optimization

              – jcoder
              Dec 27 '09 at 14:40













              @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

              – Drew Dormann
              Dec 27 '09 at 14:45





              @JB, yes. I'm avoiding stating how many times the file is "opened". That's prone to misinterpretation, and really not relevant.

              – Drew Dormann
              Dec 27 '09 at 14:45













              "variety of errors" Heh.

              – Chad Okere
              Dec 27 '09 at 15:03





              "variety of errors" Heh.

              – Chad Okere
              Dec 27 '09 at 15:03











              2














              This is done by one of the two popular techniques, both of which are under stdlib's responsibility.



              One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.



              Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)



              You must also do the same in all header files you produce. Or, headers that include yours will have a problem.






              share|improve this answer
























              • I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

                – jcoder
                Dec 27 '09 at 14:42






              • 1





                @JB: The CPP man page (gcc's pre-processor) says it does that.

                – BCS
                Dec 28 '09 at 23:11
















              2














              This is done by one of the two popular techniques, both of which are under stdlib's responsibility.



              One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.



              Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)



              You must also do the same in all header files you produce. Or, headers that include yours will have a problem.






              share|improve this answer
























              • I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

                – jcoder
                Dec 27 '09 at 14:42






              • 1





                @JB: The CPP man page (gcc's pre-processor) says it does that.

                – BCS
                Dec 28 '09 at 23:11














              2












              2








              2







              This is done by one of the two popular techniques, both of which are under stdlib's responsibility.



              One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.



              Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)



              You must also do the same in all header files you produce. Or, headers that include yours will have a problem.






              share|improve this answer













              This is done by one of the two popular techniques, both of which are under stdlib's responsibility.



              One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.



              Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)



              You must also do the same in all header files you produce. Or, headers that include yours will have a problem.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 27 '09 at 14:36









              Pavel RadzivilovskyPavel Radzivilovsky

              15.8k34861




              15.8k34861













              • I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

                – jcoder
                Dec 27 '09 at 14:42






              • 1





                @JB: The CPP man page (gcc's pre-processor) says it does that.

                – BCS
                Dec 28 '09 at 23:11



















              • I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

                – jcoder
                Dec 27 '09 at 14:42






              • 1





                @JB: The CPP man page (gcc's pre-processor) says it does that.

                – BCS
                Dec 28 '09 at 23:11

















              I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

              – jcoder
              Dec 27 '09 at 14:42





              I belive that many compliers can recongise the include guard pattern and treat it in a similar way to the pragma. Although I've not verified myself that any specific compiler does this

              – jcoder
              Dec 27 '09 at 14:42




              1




              1





              @JB: The CPP man page (gcc's pre-processor) says it does that.

              – BCS
              Dec 28 '09 at 23:11





              @JB: The CPP man page (gcc's pre-processor) says it does that.

              – BCS
              Dec 28 '09 at 23:11











              2














              As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.



              Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration



              Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.



              Also, always utilize the include guards or #pragma once for your own header files!






              share|improve this answer



















              • 1





                I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

                – Alok Singhal
                Dec 27 '09 at 15:02
















              2














              As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.



              Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration



              Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.



              Also, always utilize the include guards or #pragma once for your own header files!






              share|improve this answer



















              • 1





                I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

                – Alok Singhal
                Dec 27 '09 at 15:02














              2












              2








              2







              As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.



              Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration



              Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.



              Also, always utilize the include guards or #pragma once for your own header files!






              share|improve this answer













              As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.



              Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration



              Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.



              Also, always utilize the include guards or #pragma once for your own header files!







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 27 '09 at 14:41









              Hamish GrubijanHamish Grubijan

              4,4481783133




              4,4481783133








              • 1





                I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

                – Alok Singhal
                Dec 27 '09 at 15:02














              • 1





                I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

                – Alok Singhal
                Dec 27 '09 at 15:02








              1




              1





              I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

              – Alok Singhal
              Dec 27 '09 at 15:02





              I am not sure if including a header inside another is bad. What if a header needs stuff from another? I like my header files to be able to be #included without the user remembering their correct order. Standard libraries behave the same way!

              – Alok Singhal
              Dec 27 '09 at 15:02











              1














              As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:




              Standard headers may be included in any order; each may be included more than once in
              a given scope, with no effect different from being included only once, except that the
              effect of including <assert.h> depends on the definition of NDEBUG.




              How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".



              But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.



              For example, given a header:



              int a;


              including it twice will result in two definitions of a. This is a Bad Thing.



              The easiest way to avoid conflict like this is to use include guards as defined above:



              #ifndef H_HEADER_NAME_
              #define H_HEADER_NAME_
              /* header contents */
              #endif


              This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)



              Of course, in your code, you should ensure that the macro name for include guard satisfies this:




              • It doesn't start with E followed by an uppercase character,

              • It doesn't start with PRI followed by a lowercase character or X,

              • It doesn't start with LC_ followed by an uppercase character,

              • It doesn't start with SIG/SIG_ followed by an uppercase character,


              ..etc. (That is why I prefer the form H_NAME_.)



              As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).



              #ifndef SZ
              #define SZ 1024
              #else
              #if SZ == 1024
              #undef SZ
              #define SZ 128
              #else
              #error "You can include me no more than two times!"
              #endif
              #endif





              share|improve this answer






























                1














                As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:




                Standard headers may be included in any order; each may be included more than once in
                a given scope, with no effect different from being included only once, except that the
                effect of including <assert.h> depends on the definition of NDEBUG.




                How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".



                But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.



                For example, given a header:



                int a;


                including it twice will result in two definitions of a. This is a Bad Thing.



                The easiest way to avoid conflict like this is to use include guards as defined above:



                #ifndef H_HEADER_NAME_
                #define H_HEADER_NAME_
                /* header contents */
                #endif


                This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)



                Of course, in your code, you should ensure that the macro name for include guard satisfies this:




                • It doesn't start with E followed by an uppercase character,

                • It doesn't start with PRI followed by a lowercase character or X,

                • It doesn't start with LC_ followed by an uppercase character,

                • It doesn't start with SIG/SIG_ followed by an uppercase character,


                ..etc. (That is why I prefer the form H_NAME_.)



                As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).



                #ifndef SZ
                #define SZ 1024
                #else
                #if SZ == 1024
                #undef SZ
                #define SZ 128
                #else
                #error "You can include me no more than two times!"
                #endif
                #endif





                share|improve this answer




























                  1












                  1








                  1







                  As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:




                  Standard headers may be included in any order; each may be included more than once in
                  a given scope, with no effect different from being included only once, except that the
                  effect of including <assert.h> depends on the definition of NDEBUG.




                  How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".



                  But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.



                  For example, given a header:



                  int a;


                  including it twice will result in two definitions of a. This is a Bad Thing.



                  The easiest way to avoid conflict like this is to use include guards as defined above:



                  #ifndef H_HEADER_NAME_
                  #define H_HEADER_NAME_
                  /* header contents */
                  #endif


                  This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)



                  Of course, in your code, you should ensure that the macro name for include guard satisfies this:




                  • It doesn't start with E followed by an uppercase character,

                  • It doesn't start with PRI followed by a lowercase character or X,

                  • It doesn't start with LC_ followed by an uppercase character,

                  • It doesn't start with SIG/SIG_ followed by an uppercase character,


                  ..etc. (That is why I prefer the form H_NAME_.)



                  As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).



                  #ifndef SZ
                  #define SZ 1024
                  #else
                  #if SZ == 1024
                  #undef SZ
                  #define SZ 128
                  #else
                  #error "You can include me no more than two times!"
                  #endif
                  #endif





                  share|improve this answer















                  As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:




                  Standard headers may be included in any order; each may be included more than once in
                  a given scope, with no effect different from being included only once, except that the
                  effect of including <assert.h> depends on the definition of NDEBUG.




                  How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".



                  But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.



                  For example, given a header:



                  int a;


                  including it twice will result in two definitions of a. This is a Bad Thing.



                  The easiest way to avoid conflict like this is to use include guards as defined above:



                  #ifndef H_HEADER_NAME_
                  #define H_HEADER_NAME_
                  /* header contents */
                  #endif


                  This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)



                  Of course, in your code, you should ensure that the macro name for include guard satisfies this:




                  • It doesn't start with E followed by an uppercase character,

                  • It doesn't start with PRI followed by a lowercase character or X,

                  • It doesn't start with LC_ followed by an uppercase character,

                  • It doesn't start with SIG/SIG_ followed by an uppercase character,


                  ..etc. (That is why I prefer the form H_NAME_.)



                  As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).



                  #ifndef SZ
                  #define SZ 1024
                  #else
                  #if SZ == 1024
                  #undef SZ
                  #define SZ 128
                  #else
                  #error "You can include me no more than two times!"
                  #endif
                  #endif






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 27 '09 at 15:10

























                  answered Dec 27 '09 at 14:49









                  Alok SinghalAlok Singhal

                  67.3k14110142




                  67.3k14110142






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1966075%2finclude-files-in-different-files%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                      Alcedinidae

                      RAC Tourist Trophy