簡體   English   中英

C - 使用-Wall編譯不會警告未初始化的變量

[英]C - Compiling with -Wall doesn't warn about uninitialized variables

我有一個示例有缺陷的程序,應該給出一個關於未初始化變量的警告,但是當我編譯它時,gcc不會給我任何警告。

這是代碼:

#include <stdio.h>

int main()
{
    int foo;

    printf("I am a number: %d \n", foo);

    return 0;
}

這是我運行的: cc -Wall testcase.c -o testcase

我得不到反饋。 據我所知,這應該產生:

testcase.c: In function 'main': 
testcase.c:7: warning: 'foo' is used uninitialized in this function

它似乎在他的C教程中以類似的例子正確警告Zed Shaw。 這是我第一次嘗試的例子,並注意到它沒有按預期工作。

有任何想法嗎?

編輯:

gcc的版本:

i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)

您是否正在編譯並啟用了優化? 這是我的man gcc頁面說的:

  -Wuninitialized Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a "setjmp" call. These warnings are possible only in optimizing compilation, because they require data flow information that is computed only when optimizing. If you do not specify -O, you will not get these warnings. Instead, GCC will issue a warning about -Wuninitialized requiring -O. 

我的gcc版本是:

i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)

實際上,我剛剛在gcc 4.4.5上嘗試了這個,我確實在不使用-O情況下得到了警告。 所以這取決於你的編譯器版本。

更新您的編譯器。

$ cat test.c
#include <stdio.h>

int main(void)
{
    int foo;
    printf("I am a number: %d \n", foo);
    return 0;
}
$ gcc -Wall -o test ./test.c
./test.c: In function ‘main’:
./test.c:7:11: warning: ‘foo’ is used uninitialized in this function [-Wuninitialized]
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6.1/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.1-9ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++,go --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3) 
$ 

C標准不要求編譯器在訪問未初始化的變量時發出警告。 如果程序調用未定義的行為(假設沒有語法錯誤且沒有約束違規),甚至不需要編譯器發出警告。

使用gcc您可以使用-Wuninitialized為未初始化的變量啟用警告。 正如其他人所說,使用最新版本的gcc ,在指定-Wall時啟用-Wuninitialized

使用Clang ,完成它。 看起來像GCC中的一個錯誤,因為Clang警告它應該這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM