Loose-Info.com
Last Update 2021/05/01
TOP - 各種テスト - gcc - 警告関連のオプション - フォーマット文字列関連のオプション - -Wformat(-Wformat=1)

-Wformat(-Wformat=1)
printfやscanfなどの関数呼び出しで、引数とフォーマット文字列をチェック

テスト概要

その1
-Wformat、-Wformat=1、-Wallの各オプションを使用したコンパイル時の警告出力例

その2
フォーマット属性でprintf形式を指定された関数を含む場合の警告出力例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


コード例・出力内容中の表記

・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。

その1

-Wformat、-Wformat=1、-Wallの各オプションを使用したコンパイル時の警告出力例

sample1.c
#include <stdio.h> int main(void) { /* 関数内で使用されない変数の宣言 */ int n0; double d = 1.234; int n = 3; /* フォーマット文字列と引数の不一致 */ printf("n = %d : d = %d\n", n, d); return 0; }

オプション無しで実行
$ gcc sample1.c $ エラー・警告無し

-Wformatオプションを指定して実行
$ gcc -Wformat sample1.c sample1.c: In function ‘main’: sample1.c:12:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat=] printf("n = %d : d = %d\n", n, d); ~^ ~ %f $ -Wformatオプションによるフォーマット文字列に関する警告を出力

-Wformat=1オプションを指定して実行
$ gcc -Wformat=1 sample1.c sample1.c: In function ‘main’: sample1.c:12:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat=] printf("n = %d : d = %d\n", n, d); ~^ ~ %f $ -Wformatオプションを指定した場合と同一の出力内容

-Wallオプションを指定して実行
$ gcc -Wall sample1.c sample1.c: In function ‘main’: sample1.c:12:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat=] printf("n = %d : d = %d\n", n, d); -Wformatオプションにより出力 ~^ ~ %f sample1.c:6:6: warning: unused variable ‘n0’ [-Wunused-variable] int n0; -Wallに含まれる-Wunused-variableオプションにより出力 ^~ $

その2

フォーマット属性でprintf形式を指定された関数を含む場合の警告出力例

sample2.c
#include <stdio.h> void sampFunc(const int cnt, char *fmtst, ...) __attribute__ ((format (printf, 2, 3))); /* フォーマット属性の指定 */ void sampFunc(const int cnt, char *fmtst, ...) { } int main(void) { double d = 1.234; int n = 3; /* フォーマット文字列と引数の不一致 */ printf("n = %d : d = %d\n", n, d); /* format属性を指定した関数呼び出しのフォーマット文字列と引数の不一致 */ sampFunc(2, "n = %d : d = %d : x = %d\n", n, d); return 0; }

-Wformatオプションを指定して実行
青色部は「format属性を指定した関数」に関する警告
$ gcc -Wformat sample2.c sample2.c: In function ‘main’: sample2.c:16:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat=] printf("n = %d : d = %d\n", n, d); ~^ ~ %f sample2.c:19:29: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘double’ [-Wformat=] sampFunc(2, "n = %d : d = %d : x = %d\n", n, d); ~^ ~ %f sample2.c:19:38: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=] sampFunc(2, "n = %d : d = %d : x = %d\n", n, d); ~^ $