不符合ANSI/ISO的源代碼
/*
* pedant.c - use -ansi, -pedantic or
-pedantic-errors
*/
#include <stdio.h>
void
main(void)
{
long long int i = 0l;
printf("This is a non-conforming
c program\n");
}
使用gcc pedant.c -o
pedant這個命令時,編譯器會警告main函數的返回類型無效:
$gcc pedant.c -o pedant
pedant.c:In
function 'main':
pedant.c:7 warning:return type of 'main' is not
'int'
現在給gcc加上-ansi選項:
$gcc -ansi pedant.c -o pedant
$gcc pedant.c -o
pedant
pedant.c: In function 'main'
pedant.c:7 warning: return type of
'main' is not
'int'
gcc再次給出了同樣的警告信息,并忽略了無效的數據類型.
-ansi,-pedantic以及-pedantic-errors編譯選項并不能保證被編譯的程序的ANSI/ISO兼容性,它們僅被用來幫助程序員離這個目標更近.
$gcc
-Wall pedant.c -o pedant
pedant.c:7: warning: return type of 'main' is not
'int'
pedant.c: In function 'main':
pedant.c:8 warning: unused variable
'i'
-Wall系列選項的另一個極端是-w選項,它能關閉所有的警告信息。-W{warning}選項的作用是打開warning所指出的用戶感興趣的特殊警
告信息,比如隱身函數說明(-Wimplicit-function-declaration)或者隱身聲明返回類型的函數(-Wreturn-
type).前者的作用在于它提示出定義了一個函數卻沒有事先聲明或者忘記了包含適當的頭文件.后者的作用在于指出聲明的函數可能沒有指定它的返回類型,
此時默認的返回類型為int.
提示:如果只想檢查語法而實際上不做如何編譯工作,那么可以調用帶有-fsyntax-only參數的GCC.
選項
說明
-Wcomment
如果出現了注解嵌套(在第一個/*之后又出現了第二個/*)則發出警告
-Wformat
如果傳遞給printf及及其相關函數
的參數和對應的格式字符串中指定的類型不平配則發出警告
-Wmain
如果main的返回類型不
是int或者調用main時使用的參數數目不正確則不出警告
-Wparentheses
如果在出現了賦值(例如,(n=10))的地方使用了括號,而那里根據前后關系推斷應該是比較(例如,(n==100))而非賦值的時候,或者如果括號能夠解決運算優先級問題的時候,發出警告
-Wswitch
如果swtich語句少了它的一個或多
個枚舉值的case分支(只有索引值是enum類型時才適用)則發出警告
-Wunused
如果聲明的變量沒有使用,或者函數聲明
為static類型但卻從未使用,則發出警告
-Wuninitialized
如果使用的自動變量沒有初始化則發出警告
-Wundef
如果在#if宏中使用了未定義的變量作判斷則發出警告
-Winline
如果函數不能被內聯則發出警告
-Wmissing-declarations 如果定義了全局函數但卻沒有在任何頭文件中聲明它,則發出警告
-Wlong-long
如果使用了long long類型則發出警告
-Werror
將所有的警告轉變為錯誤
常見的編程錯誤:
/*
* blunder.c - Mistakes caught by
-W(warning)
*/
#include <stdio.h>
#include
<stdlib.h>
int main(int argc, char *argv[])
{
int i,
j;
printf("%c\n", "not a character"); /* -Wformat */
if(i =
10) /*
-Wparenthesses */
printf("oops\n");
if(j !=
10)
/* -Wuninitialized */
printf("another oops\n");
/* /*
*/ /*
-Wcomment */
no_decl(); /*
-Wmissing-declaration */
return (EXIT_SUCCESS);
}
void
no_decl(void)
{
printf("no_decl\n");
}
$gcc blunder.c -o
blunder
blunder.c:27: warning: type mismatch with previous implicit
declaration
blunder.c:21: warning: previous implicit declaration of
'no_decl'
blunder.c:27: warning: 'no_decl' was previously implicitly declared
to return
'int'
gcc只發出了和隱式聲明no_decl函數有關的警告.它忽略了其他潛在的錯誤,這些錯誤包括:
.傳遞給printf的參數類型(一個字符串)和格式化字符串定義的類型(一個字符)不匹配.這會產生一個-Wformat警告.
.變量i和j使用前都沒有初始化.它們中的任何一個都產生-Wuninitialized警告.
.在根據前后關系推斷應該對變量i的值做比較的地方,卻對變量i進行賦值.這應該會產生一個-Wparentheses警告.
.在注釋嵌套開始的地方應該會產生一個-Wcomment警告.