What changes you can do in the header files to avoid the redefinition that compiler will give when both the header files are included in the same program keeping the declaration of both the functions same?

Content of h1.h
------------------------------------------------
h1.h
#include <iostream>
using namespace std;
int func(int a){
    cout<<"Multiplied by 2";
    return 2*a;
}
------------------------------------------------
 
Content of h2.h
------------------------------------------------
h2.h
#include <iostream>
using namespace std;
int func(int a){
    cout<<"divided by 2";
    return a/2;
}
------------------------------------------------

a) Cannot be handled because C++ does not allow this
b) Declare both the function inside different namespaces
c) Include one header files where they are needed so that no clashes occur
d) Make the header files name same

1 thought on “What changes you can do in the header files to avoid the redefinition that compiler will give when both the header files are included in the same program keeping the declaration of both the functions same?”

  1. b
    Explanation: Define both the function in different namespaces under their respective header files. So whenever we need them we can use the name of their respective namespaces to call them. This will resolve the error keeping function declarations same.
    Modified Header files :

    h1.h
    Content of h1.h
    ————————————————
    #include
    using namespace std;
    namespace A{
    int func(int a){
    cout<<"Multiplied by 2";
    return 2*a;
    }
    }
    ————————————————

    Content of h2.h
    ————————————————

    #include
    using namespace std;
    namespace B{
    float func(float a){
    cout<<"divided by 2";
    return a/2;
    }
    }
    ————————————————

Leave a Comment