Home > Enterprise >  Use a private function in header as #define in c
Use a private function in header as #define in c

Time:10-23

I have a function f which is:

void f(int x, int y, int z){
    //bla bla bla
}

and some other functions which use f:

void g(int x, int y, int z){
    f(x, 10, 10); //10, 10 are hard coded
}
void h(int x, int y){
    f(x, y, 20); //20 is hard coded
}

IMPORTANT: f is must stay private and hidden to other files.

Now, in the header file, I JUST write the prototypes of h and g. Everything is OK.

I decided to use #define for h & g, cause it's much easier and more standard. So I removed the functions and wrote this on the header:

#define h(x)       f(x, 10, 10)
#define g(x, y)    f(x, y, 10)

The problem is, as you know, I have to write the prototype of f in the header. f must be private. Is there any way that I can use #define in this scenario at all? Like using #def, #undef, ...

Note: Feel free to change the topic

CodePudding user response:

Don't use macros then.

Do it like this:


// header.h
void g(int x, int y, int z);
void h(int x, int y);

// implementation.c
#include "header.h"

static void f(int x, int y, int z){
    //bla bla bla
}

void g(int x, int y, int z){
    f(x, 10, 10); //10, 10 are hard coded
}

void h(int x, int y){
    f(x, y, 20); //20 is hard coded
}

Note the use of static on f. Without f being declared static, it will be visible to all the other translation units in your program regardless. If you really want to hide it, you must make it static.

CodePudding user response:

You do NOT need to write the prototype of f in a header file.

In secret_data.c:

static void f(int x, int y, int z){   // F is defined here.
    //bla bla bla
}
// Because f is static, it is NOT visible outside this file.
    
void g(int x, int y, int z){
    f(x, 10, 10); // F is used here
}
void h(int x, int y){
    f(x, y, 20); // F is used here
}

CodePudding user response:

#define creates a macro, which is substituted by the compiler. The code the macro creates doesn't even have to be a full C statement, it just acts as though the person using the macro had actually typed the expanded version.

It follows that a macro has to produce code that would be valid if the user of the macro was typing it in full. You can't "hide" anything in a macro, because it has to be expanded before the C code is compiled.

So if you want the function f() to be private, your original solution of using functions for g() and h() is the correct one.

  • Related