在 header 中使用私有函数作为 c 中的 #define

Use a private function in header as #define in c

我有一个函数 f 是:

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

和其他一些使用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
}

重要提示: f 必须保持私密且对其他文件隐藏。

现在,在header 文件中,我只是 编写了hg 的原型。一切正常。

我决定对 hg 使用 #define,因为它更简单也更标准。所以我删除了函数并将其写在 header:

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

问题是,如您所知,我必须在 header 中编写 f 的原型。 f 必须是私有的。有什么办法可以在这种情况下使用#define 吗?比如使用 #def, #undef, ...

注意:随意更改主题

那就不要使用宏了。

这样做:


// 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
}

请注意 fstatic 的使用。如果没有 f 声明 static,它将对您程序中的所有其他翻译单元可见。如果真要隐藏,就必须静态化。

您不需要在头文件中编写 f 的原型。

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
}

#define 创建一个 ,它 被编译器 替换。宏创建的代码甚至不必是完整的 C 语句,它就像使用宏的人实际上键入了扩展版本一样。

因此,宏必须生成在宏的用户完整键入宏的情况下有效的代码。您不能在宏中“隐藏”任何内容,因为在编译 C 代码之前 必须展开它。

因此,如果您希望函数 f() 是私有的,那么将函数用于 g() 和 h() 的原始解决方案是正确的。

I decided to use #define for h & g, cause it's much easier and more standard.

#define 可能更容易,但并不是更标准。事实上,它很容易出错并且很难调试。 #define 通常用于更快的处理,与函数调用相反,它不使用 RAM(堆栈)或处理时间,因为它只是替换了编译器预处理器。

有了这一点,可以公平地说,当我们想让事情更快地工作时,可以使用#define。

出于您的目的,并且因为您希望 f() 保持私有,除了使用 inline 关键字之外,还有另一种方法可以使事情变得更快。

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

inline 关键字指示编译器通常通过代码替换来优化对 f() 的任何调用,如 #define。 请注意,内联函数不一定由编译器内联。 有关更多信息,请参阅 http://www.greenend.org.uk/rjk/tech/inline.html

尽管您不必将 h & g 创建为函数。你可以这样做:

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

void fInterface(int x, int y, int z){
    f(x, y, z);
}

然后在头文件中:

void fInterface(int x, int y, int z); // Prototype

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

此代码的性能几乎与导出 f() 本身相同。

希望对您有所帮助!