'how can i not show a function in header A.h that is used in a function in header B.h but not in main.cpp C++?

so I have two header file (A.h and B.h) and i include B.h in the main.cpp file

//A.h

void foo()
{
    //do something
}

//B.h
#include "A.h"

void foo1()
{
    foo();
    //do something else
}

//main.cpp
#include "B.h"

int main()
{
    foo1();
}

in my testings i haven't found a way to hide foo() in main i should also mention that the functions foo() and foo1() are helper function but i want that the only way i can use foo() is when i include directly A.h is there a way to do this?

c++


Solution 1:[1]

Simple solution: Don't define (implement) functions in header files, only declare them. Define them in source files.

Then you would have e.g. a header file A.h:

void foo();

A source file A.cpp:

void foo()
{
    // Do foo stuff...
}

And a B.h header file:

void bar();

And a B.cpp source file:

#include "A.h"

void bar()
{
    // Do bar stuff

    // Call foo
    foo();

    // Do more bar stuff
}

Then finally the main source file where you only include B.h:

#include "B.h"

int main()
{
    bar();

    // Can't call foo, as it's not declared
}

Solution 2:[2]

is there a way to do this?

Yes, you can make use of headers files and source files(.cpp) as shown below.

A.h

#ifndef A_H
#define A_H
//this is a declaration
void foo();
#endif

A.cpp

#include "A.h"
//this is the implementation
void foo()
{
    //do something
}

B.h

#ifndef B_H
#define B_H
//this is a declaration
void foo1();
#endif

B.cpp

#include "A.h"

//this is implementation
void foo1()
{
    foo();
    //do something else
}

main.cpp

//main.cpp
#include "B.h"

int main()
{
    foo1();
}

Working demo

Note

It is recommended that we should use header guards in header files.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some programmer dude
Solution 2 Anoop Rana