2013-06-01 96 views
25

我开始Zed Shaw的Learn C The Hard Way。我已经下载了XCode和命令行工具。但是,当我编译第一个程序:GCC警告:函数'puts'的隐式声明在C99中无效

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

我得到这样的警告:

ex1.c中:2:1:警告:函数 '使' 隐性声明是无效的 在C99 [-Wimplicit函数声明]

该程序并编译和正确执行。

我使用的是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)

请帮忙。

+0

当参数未被使用时,使用'int main(int argc,char * argv [])'是轻度愚蠢的;它应该是'int main(void)'或者甚至是'int main()'。不过,这可能是另一天的争论。我注意到GCC 5.x使用C11('-std = gnu11')作为默认的编译模式。 'clang'(伪装成'gcc')使用C99。 C99和C11都要求在使用之前声明所有函数(main()除外)。 –

回答

40

您需要包括stdio.h中,即

#include <stdio.h> 

在开始导入函数定义。

+2

同样在第2课中,Zed指出,您可以使用include语句摆脱警告。所以我用正确的答案来记录你。 – grok12

3

这本“书”应该改名为学习仇恨C通过以下无意义的例子是公然错误的。

在现代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; 
} 

将在1989年一直只是普通,在1999年(即写这个答案前18年,几乎同样多年在“书”写之前)C标准被修改了。在C99修订版中,这种implicit function declaration是非法的 - 和naturally it remains illegal in the current revision of the standard (C11)。因此,使用puts而不#include荷兰国际集团相关的头,即前面加上#include <stdio.h>(或声明puts函数int puts(const char*);)为约束错误

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

+0

那是链接官方标准网站/存储库thingy吗? – Ungeheuer

+0

@Ungeheuer不,不幸的是[官方标准](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents)花钱。这是C11 final * draft *的HTML版本,其工作名称为** n1570 **。 –

+0

谢谢你。最后一个问题。链接的网站是否有以前的标准?我没有看到从那里导航的方法。 – Ungeheuer

相关问题