2020年1月29日 星期三

Makefile 中的 CFLAGS 變數套用順序

當使用 make 編譯程式時,若有多處定義 CFLAGS,則最終結果應該為何呢?

針對此疑問,整理相關資訊如下:

1. 若在命令列有先指定 CFLAGS, 則 Makefile 內的變數就不會套用。
例如: 執行 make CFLAGS=-g ,則 Makefile 內的 CFLAGS 便會失效 
原文如下:
If a variable has been set with a command argument (see Overriding Variables), then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an override directive, which is a line that looks like this:
https://www.gnu.org/software/make/manual/html_node/Overriding.html


2.  若在命令列有先指定 CFLAGS, 但仍想要讓 Makefile 內的 CFLAGS有效,可使用 override 關鍵字
原文如下:
Variable assignments marked with the override flag have a higher priority than all other assignments, except another override. Subsequent assignments or appends to this variable which are not marked override will be ignored.
https://www.gnu.org/software/make/manual/html_node/Override-Directive.html#Override-Directive 
實際例子如下
https://github.com/buildroot/buildroot/blob/master/package/irrlicht/0001-override-CPPFLAGS-CXXFLAGS-and-CFLAGS-in-Makefile.patch

3. 若編譯時,命令列沒有帶入 CFLAGS,則直接參考 Makefile 內的 CFLAGS 設定即可。