5 4 條件編譯

2021-10-21 02:29:54 字數 1868 閱讀 9273

1)#ifndef 含義是 if not define,如果沒有定義

2)#ifdef 含義是 if define,如果已經定義

3)#if 配合函式 defined() 使用,if defined(macro) == ifdef macro,如果已經定義了巨集 macro

三者均要以 endif 進行結尾。

// 標頭檔案中必有的條件編譯,以免一些標頭檔案被重複引用

#ifndef chapter5_include_factorial_h_

#define chapter5_include_factorial_h_

unsigned int factorial(unsigned int n);

unsigned int factorialbyiteration(unsigned int n);

#endif //chapter5_include_factorial_h_

// #if的用法

#ifdef debug // == if defined(debug)

puts(message);

#endif

不存在 define debug 該行**的情況下,dump 函式的內容不會輸出;定義了 debug 的情況下,dump 函式內容才會輸出。

#define debug  // 該巨集定義存在的情況下,輸出結果為 start! hello end

// 該巨集定義不存在的情況下,輸出結果為 hello

void dump(char *message)

int main()

如果不在**中去增加或刪除巨集 debug,也可以對 cmakelists.txt 進行更改,定義巨集 debug 或不定義該巨集。

cmake_minimum_required(version 3.17)

get_filename_component(projectid $ name)

string(replace " " "_" projectid $)

project($ c)

set(cmake_c_standard 90)

include_directories("include")

file(glob files "$/*.c")

foreach(file $)

get_filename_component(name $ name)

add_executable($ $ src/factorial.c)

# 新增該句即意味著定義了巨集 debug

target_compile_definitions($ public debug)

endforeach()

在 c++ 環境下執行的**會多有 extern c{}; c 環境下沒有該**。

#ifdef __cplusplus  // 如果是在 c++ 環境下,會查詢是否定義了巨集 __cplusplus 

extern "c" ;

#endif

可以利用 __stdc_version__ 檢視,順便附贈乙個在巨集中使用 ifelse 的 demo(注意, __stdc_version__ 需使用 mingw 編譯器,msvc 編譯器不支援)

int main()
可以利用條件編譯判斷**執行的平台,是在 windows 環境還是 linux 環境,或者 mac 環境,從而呼叫他們系統本身的 api 進行使用。

14 條件編譯

巨集操作符包括 和 這兩個操作符都是對巨集不代表數字的引數進行 處理的 操作符可以把乙個引數轉換成字串字面值 在引數前後各加乙個 操作符可以把乙個代表識別符號的引數和其他內容 合併得到乙個新識別符號 條件編譯可以在編譯的時候決定哪些語句需要編譯 哪些語句不需要編譯 條件編譯是使用預處理指令實現的 i...

C語言 (1) 條件編譯

第一種形式 解釋 如果識別符號被 define語句定義過,則編譯程式段1 否則編譯程式段2 incelud define num ok int main ifdef num printf hello world else printf hello china endif return o 因為已經定...

C語言 09條件編譯

條件編譯的概念 通常我們希望程式的其中一部分 只有在滿足一定的情況下才進行編譯,否則不參與編譯,只有參與編譯的 最終才能被執行 這就是條件編譯 基本用法 if condication01 code01.elif condication02 code02.else code03.endif 1 inc...