警告:编译C源代码时隐式声明函数 [英] warning: implicit declaration of function when compiling C source

查看:67
本文介绍了警告:编译C源代码时隐式声明函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C.这是我今天面临的一个问题.当我尝试为 main.c 创建目标文件时,我得到:

I'm learning C. Here is a problem that I face today. When I try to create object file for main.c I get:

cc -Wall -c main.c
main.c:6:18: warning: implicit declaration of function 'sum' is invalid in C99 [-Wimplicit-function-declaration]

如何避免这种情况?

functions.c:

functions.c:

int sum(int x, int y)
{
  return x + y;
}

main.c:

#include <stdio.h>
#include "functions.h"

int main()
{
   printf("%d", sum(1,1));
   return 0;
}

function.h存在,但我没有在这里添加.

function.h exists but I didn't add it here.

推荐答案

通常,您的 functions.h 将包含:

extern int sum(int x, int y);

可能用头文件保护器包装,并且可能省略了 extern * .您应该在定义函数的文件中以及在使用该函数的任何文件中包含标头.这两个部分都至关重要.它们允许标头确保该函数的使用与该函数的定义一致.

possibly wrapped with header guards, and possibly omitting extern*. You should include the header in the file that defines the function, and also in any file that uses it. Both parts are crucial; they allow the header to ensure that the uses of the function agree with the definition of the function.

C99要求在使用函数之前先声明或定义函数,就像C ++一样.

C99 requires functions to be declared or defined before they are used, rather like C++.

FWIW:我通常使用GCC进行编译,并且通常使用以下选项:

FWIW: I usually compile with GCC and usually use the options:

gcc -g -O3 -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
    -Wold-style-definition -Wold-style-declaration -Werror \
    ...other arguments as appropriate...

-Werror 意味着我的代码编译时没有警告!您还会看到我在单个文件程序中定义的函数中添加 static 以避免警告(又称错误),尽管我并不总是在评论为什么要进行更改.

The -Werror means my code compiles without warnings! You'll also see me add static to functions defined in a single-file program to avoid warnings (aka errors) though I don't always bother to comment on why I make that change.

* 通常,标头应包含标头防护.对于既不需要任何其他 headers 的标头,也不需要定义任何标头类型,则几乎可以省略标题保护符(无论如何我都会放置标题保护符,但是只要您意识到这些问题,也可以省略它们).我更愿意在函数上使用 extern ,尽管这不是必需的.对于变量,它是

* Normally, headers should include header guards. For a header that neither needs any other headers nor defines any types, it is almost permissible to omit the header guards (I'd put them in anyway, but as long as you're cognizant of the issues, omitting them would be OK too). I prefer to use extern even on functions, though it is not necessary. For variables, it is crucial.

这篇关于警告:编译C源代码时隐式声明函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆