我有一個列印除錯日志的函式,必須根據環境變數進行切換。與其在每次呼叫print_trace()時檢查環境變數,不如用什么方法來存盤它并重復使用該值?
void print_trace(const char* msg)。
{
const char* s = getenv("DEBUG_TRACE"/span>)。
if(!strcmp(s,"ON")
printf(msg)。
沒有main()因為這是一個共享庫。
uj5u.com熱心網友回復:
你可以將決定的結果保存在一個靜態變數中。
void print_trace(const char* msg)。
{
static int debug_on = -1; //-1 == not yet set
if (debug_on == -1) {
const char* s = getenv("DEBUG_TRACE"/span>)。
debug_on = s && (strcmp(s, "ON") == 0) 。
}
if(debug_on)
printf("%s"/span>, msg);
}
uj5u.com熱心網友回復:
你可以使用執行緒安全的call_once功能,該功能在C11中被添加。
示例:
#include <threads.h>/span>
static bool debug_mode; //你的除錯模式標志。
void set_debug_mode(void) { // this is only called once
const char *s = getenv("DEBUG_TRACE"/span>)。
debug_mode = s && !strcmp(s, "ON");
}
void print_trace(const char* msg> {
static once_flag flag = ONCE_FLAG_INIT;
call_once(&flag, set_debug_mode); //呼叫一次來設定debug_mode。
if(debug_mode)
printf(msg)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322467.html
標籤:
下一篇:使用帶有標記粘貼運算子的宏
