0

Hello everyone iam just looking through the header guards application in c++,I know that header guards are used to include content of any file at once,i have the following scenario as,

a.h

#include<string>
#include "b.h"
std::string getA()
{
    return "A";
}

b.h

#include<string>
#include "a.h"
#ifndef B_H
#define B_H
std::string getB()
{
    return "B";
}
#endif

and both.cpp

#include<iostream>
#include"b.h"
#include"a.h"
using namespace std;
int main()
{
    cout<<getA();
    cout<<getB();
    return 0;
}

please explain me how does the final both.cpp contains as we have two times called "#include "b.h" ".I think iam making sense here.Thanks in advance.Please help needed guys. Since a.h has no header guard and the function defination of getA should be included 2 times in both.cpp, but the program ran successfully.Please help me in figuring out final both.cpp code.

Anil
  • 1,748
  • 8
  • 32
  • 67
  • `a.h` includes `b.h` includes `a.h` includes `b.h`... – NathanOliver Sep 01 '16 at 17:26
  • On a quick re-read, there will be a problem here will be with the lack of a header guard on a.h in addition to the circular reference. – user4581301 Sep 01 '16 at 17:27
  • @user4581301 ,i can able to run the program and get the desired output.,Even i thought it should cause promblem and compiler error will come but it didnt came. – Anil Sep 01 '16 at 17:28
  • Sadly that doesn't mean that the program is correct, SubSea. Some code looks like it works through dumb bad luck. You're going to wind up with a.h being included twice. It works in this case because a.h is trivial. It doesn't do much, so including it twice does no damage. The program just compiles a microscopic bit slower. A less trivial a.h could easily cause hard-to-diagnose compiler errors. – user4581301 Sep 01 '16 at 17:33
  • Also worth thinking about why a.h includes b.h when a.h doesn't use any of the stuff declared in b.h and vice-versa. The circular reference is completely unnecessary. – user4581301 Sep 01 '16 at 17:36
  • @user4581301 ,yes ,the program is not correct but what actually is going behind the scenes?can you please explain how a less trivial a.h could cause the promblem?Thanks for the response. – Anil Sep 01 '16 at 17:36
  • i was just learning header guards and just gave it a shot,i am not using anything from b.h in a.h – Anil Sep 01 '16 at 17:38
  • Link I had posted explained how headers were included. Looks like it got deleted when the dupe tag went up. Short version: Every time the compiler sees `#include` it pastes the contents of the included file into the including file. This means the same things may be declared twice. This can confuse the compiler because it now doesn't know which one to use. In a nastier case, you can wind up with a chain of `#include`s that go on forever and generate an infinitely long file. – user4581301 Sep 01 '16 at 18:07

0 Answers0