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?
CodePudding user response:
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
}
CodePudding user response:
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();
}
Note
It is recommended that we should use header guards in header files.