首页 文章

GCC警告:隐含的函数声明'puts'在C99中无效

提问于
浏览
28

我开始是Zed Shaw的Learn C The Hard Way . 我已经下载了XCode和命令行工具 . 但是当我编译第一个程序时:

int main(int argc, char *argv[]) {
     puts("Hello world."); 
     return 0;
 }

我收到这个警告:

ex1.c:2:1:警告:C99中函数'puts'的隐式声明无效[-Wimplicit-function-declaration]

该程序可以正确编译和执行 .

我正在使用OSX 10.8.3 . 输入 'gcc -v' 给出:

使用内置规格 . 目标:i686-apple-darwin11配置:/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix = / Applications / Xcode.app / Contents /Developer/usr/llvm-gcc-4.2 --mandir = / share / man --enable-languages = c,objc,c,obj-c --program-prefix = llvm- --program-transform-name = / ^ [cg] [^.-] * $ / s / $ / - 4.2 / --with-slibdir = / usr / lib --build = i686-apple-darwin11 --enable-llvm = / private / var / tmp /llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix = i686-apple-darwin11- --host = x86_64-apple-darwin11 --target = i686-apple-darwin11 - with-gxx-include-dir = / usr / include / c /4.2.1线程模型:posix gcc版本4.2.1(基于Apple Inc. build 5658)(LLVM build 2336.11.00)

请帮忙 .

2 回答

  • 42

    你需要包括stdio.h,即

    #include <stdio.h>
    

    在开始导入函数定义 .

  • 5

    此"book"应重命名为 Learn To Hate C By Following Meaningless Examples That Are Blatantly Wrong.

    现代C中的正确代码简单明了

    #include <stdio.h>        // include the correct header
    
    int main(void) {          // no need to repeat the argument mantra as they're not used
        puts("Hello world."); 
    }                         // omit the return in main as it defaults to 0 anyway
    

    而原始的例子

    int main(int argc, char *argv[]) {
        puts("Hello world."); 
        return 0;
    }
    

    在这个答案的写作之前18年(也就是在写这篇文章的前几年),C标准已经修改了 . 在C99修订版中,这种implicit function declaration被认定为非法 - 和naturally it remains illegal in the current revision of the standard (C11) . 因此,使用 puts without #includeing 相关 Headers ,即前面的 #include <stdio.h> (或用 int puts(const char*); 声明 puts 函数)是 constraint error .

    约束错误是必须导致编译器输出诊断消息的错误 . 此外,这样的程序被认为是一个程序 . 然而,关于C标准的特殊之处在于它允许C编译器也成功编译无效程序,尽管编译器也可以拒绝它 . 因此,这样的例子在一本本应向初学者教授C的书中几乎不是一个好的起点 .

相关问题