我有一個功能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必須保持私密并且對其他檔案隱藏。
現在,在頭檔案,我JUST寫的原型h和g。一切都好。
我決定使用#definefor h& g,因為它更容易和更標準。所以我洗掉了這些函式并在標題上寫了這個:
#define h(x) f(x, 10, 10)
#define g(x, y) f(x, y, 10)
問題是,如您所知,我必須f在標題中撰寫 的原型。f必須是私人的。有什么辦法可以在這種情況下使用 #define 嗎?就像使用#def, #undef, ...
uj5u.com熱心網友回復:
那就別用宏了。
像這樣做:
// 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
}
注意staticon的使用f。無需f宣告static,程式中的所有其他翻譯單元都可以看到它。如果你真的想隱藏它,你必須讓它靜態。
uj5u.com熱心網友回復:
我決定對 h & g 使用 #define,因為它更容易和更標準。
#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() 本身幾乎相同的性能。
希望你覺得這有幫助!
uj5u.com熱心網友回復:
#define 創建一個宏,由編譯器替換。宏創建的代碼甚至不必是完整的 C 陳述句,它只是表現得好像使用宏的人實際上鍵入了擴展版本。
因此,如果宏的用戶完整鍵入,宏必須生成有效的代碼。您不能在宏中“隱藏”任何內容,因為在編譯 C 代碼之前必須對其進行擴展。
因此,如果您希望函式 f() 是私有的,那么您對 ??g() 和 h() 使用函式的原始解決方案是正確的。
uj5u.com熱心網友回復:
您不需要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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334866.html
上一篇:如何列印多個函式的回傳值?
下一篇:解密即將到來的文本顫振
