volatile
asmlinkage
static
inline
__visible
extern
__noreturn
volatile
volatile
用於告訴編譯器每一次存取該變數都需要從記憶體讀取,而非暫存器,也就是說在使用前一定會有 load memory (mov
in x86, lw
in RISC-V) 的指令發生,考慮以下程式碼:
當我們使用 gcc -O0
編譯時,輸出結果是
此時沒有開啟編譯器最佳化,故每次存取都是從記憶體中取得而非暫存器,當使用 gcc -O3
時,輸出會是
雖然值被改變了,但由於其是 const
,編譯器認為該值不會被變動,故不再從記憶體中取得,直接由暫存器取得,再考慮其 asm code:
gcc -O0
gcc -O3
可以見到在沒有開啟編譯器最佳化時,在輸出之前:
第 34 行從記憶體再讀取了一次,但開啟編譯器最佳化後僅有 movl $10, %edx
。
我們使用 volatile
稍微改寫該 C 語言:
依然開啟 -O3
,其 asm code
可以見到再輸出之前皆有 movl 4(%rsp), %edx
。
一個有趣的地方是,在沒有開啟編譯器最佳化時,type casting 是
此處的 leaq
和 movq
都是 64 位元指令,因其操作的 &local
是 64 位元之地址。
asmlinkage
__visible
即 __attribute__((__externally_visible__))
,用於告知編譯器不要移除該函式或變數,即便當它們沒有被顯式 (explicitly) 呼叫或使用;因為事實上它們可能被隱式 (implicitly) 呼叫或使用,舉例來說:
extern
Code Organization: By declaring functions and variables in header files with extern, and defining them in corresponding source files, you can keep your code organized and maintainable. Other source files that need to use these functions or variables can simply include the appropriate header files.
Avoiding Multiple Definitions: In large projects with multiple source files, extern can be used to prevent multiple definitions of the same function or variable. If a function or variable is defined in a header file that's included in multiple source files, it will lead to multiple definition errors. By using extern, you can ensure that the function or variable is only defined once in a source file, while still allowing it to be used in other files that include the header.
Sharing Variables Between Files: extern can be used to share global variables between different source files. You can define a global variable in one source file, and then use extern in other source files to use that same variable.