What I want
I have two files: file.h
and file.c
. I want to define a function in file.h
that is going to have its definition in file.c
but I don't want the function to be included when I include file.h
in other file.
Example:
file.h
#ifndef HEADER_INCLUDED
#define HEADER_INCLUDED
// This function should be declared here and defined in "file.c"
// but only used there (not in any other source file).
int private_func();
// This function can be used every where (if included of course)
// but it needs to be able to access the "private_func()".
int public_func();
#endif // HEADER_INCLUDED
file.c
#include "file.h"
int private_func()
{
int a = 2;
int b = 3;
return a b;
}
int public_func()
{
// this functons uses the "private_func()" result to give its result
int c = private_func();
int d = private_func();
return c d;
}
#endif // HEADER_INCLUDED
other.c
This file should not import private_func()
when including its header
#include "file.h"
int main()
{
// can call the "public_func()"
int result1 = public_func();
// but cannot call "private_func()"
int result2 = private_func();
return 0;
}
In short
I don't want private_func() to be imported by a file other than "file.c". (if possible)
CodePudding user response:
You could use the pre-processor. In header:
#ifndef HEADER_INCLUDED
#define HEADER_INCLUDED
#ifdef _USE_PRIVATE_
// This function should be declared here and defined in "file.c"
// but only used there (not in any other source file).
int private_func();
#endif
// This function can be used every where (if included of course)
// but it needs to be able to access the "private_func()".
int public_func();
#endif // HEADER_INCLUDED
In the implementation file:
#define _USE_PRIVATE_
#include "file.h"
int private_func()
{
int a = 2;
int b = 3;
return a b;
}
int public_func()
{
// this functons uses the "private_func()" result to give its result
int c = private_func();
int d = private_func();
return c d;
}
#endif // HEADER_INCLUDED
other.c would not change. Including the header without the special define would omit the private definition.