是否有gcc编译器选项可帮助捕获形式参数和实际参数类型的不匹配? [英] Is there a gcc compiler option that help capture formal and actual parameter type mismatch?

查看:139
本文介绍了是否有gcc编译器选项可帮助捕获形式参数和实际参数类型的不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//file1.c
#include <stdio.h>
void p(int a)
{
  printf("%d\n",a);
}

//file2.c
 extern void p(float x); // external declaration doesn't match definition
int main(){
  float b;
  b=3.333f;
  p(b);
}

此处外部声明是错误的,因为它与实际的函数定义不同.我编译并链接两个文件:

Here the external declaration is wrong in that it is different from the actual function definition. I compile and link the two files with:

gcc -Wconversion -Wall -std=c99 file1.c file2.c

不发出警告.是否有任何gcc编译器选项可以帮助您在编译/链接期间捕获这种不匹配?

No warning is raised. Is there any gcc compiler option that can help capture this mismatch during compiling/linking?

推荐答案

在编译file2.c时,编译器不可能观察到其中的声明与file1.c中的声明不匹配,因为,在编译file2.c时,编译器不了解file1.c的内容.

It is not possible for a compiler to observe, while compiling file2.c, that a declaration in it does not match a declaration in file1.c, because, while compiling file2.c, the compiler has no knowledge of the contents of file1.c.

某些链接器具有可以帮助解决此问题的功能.但是,这不是链接C对象的常见做法. (也许应该这样.)

Some linkers have features that can help with this. However, this is not a common practice for linking C objects. (Perhaps it should be.)

这种不匹配通常通过使用头文件来处理.压倒性的普遍做法是包括标头中的声明,而不是在其他源文件中手动输入它们.为此:

This sort of mismatch is generally handled by using header files. The overwhelming common practice is to include declarations from a header, not to manually enter them in other source files. To do this:

  • 创建file1.h并将void p(int a);放入其中.
  • 在file1.c中,插入#include "file1.h".
  • 在file2.c中,插入#include "file1.h"并删除p的声明.
  • Create file1.h and put void p(int a); in it.
  • In file1.c, insert #include "file1.h".
  • In file2.c, insert #include "file1.h" and remove the declaration of p.

将file1.h包含在file1.c中的目的是使编译器既可以看到file1.h中的声明,也可以看到file1.c中的定义,并且会抱怨它们是否不兼容.

The purpose of including file1.h in file1.c is so that the compiler will see both the declaration in file1.h and the definition in file1.c, and it will complain if they are incompatible.

然后,由于file1.h包含在file2.c中,因此我们可以确保在编译file2.c时看到的声明与file1.c中的定义兼容.

Then, since file1.h is included in file2.c, we are assured the declaration seen while compiling file2.c is compatible with the definition in file1.c.

这篇关于是否有gcc编译器选项可帮助捕获形式参数和实际参数类型的不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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