在头文件中的函数原型不匹配的定义,如何抓住这一点? [英] Function prototype in header file doesn't match definition, how to catch this?

查看:364
本文介绍了在头文件中的函数原型不匹配的定义,如何抓住这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我发现这个问题,这是类似的,但不是重复:
<一href=\"http://stackoverflow.com/questions/7148285/how-to-check-validity-of-header-file-in-c-programming-language\">How检查头文件的有效性C编程语言)

(I found this question which is similar but not a duplicate: How to check validity of header file in C programming language )

我有一个功能的实现,以及一个非匹配原型(名称相同,不同类型的),其是在头文件中。头文件由使用的功能,但不包括定义该函数的文件中C文件包括在内。

I have a function implementation, and a non-matching prototype (same name, different types) which is in a header file. The header file is included by a C file that uses the function, but is not included in the file that defines the function.

下面是一个最小的测试用例:

Here is a minimal test case :

header.h:

void foo(int bar);

FILE1.C:

File1.c:

#include "header.h"
int main (int argc, char * argv[])
{
    int x = 1;
    foo(x);
    return 0;
}

文件2.C:

#include <stdio.h>

typedef struct {
    int x;
    int y;
} t_struct;

void foo (t_struct *p_bar)
{
    printf("%x %x\n", p_bar->x, p_bar->y);
}

我可以用VS 2010,没有错误或警告编译这一点,但勿庸置疑它出现segfaults当我运行它。

I can compile this with VS 2010 with no errors or warnings, but unsurprisingly it segfaults when I run it.


  • 编译器是其正常(这个我明白)

  • 链接器并没有抓住它(这个我有点惊讶)

  • 的静态分析工具(Coverity公司)没有抓住它(这让我很惊讶)。

我怎么能捕获这些类型的错误?

How can I catch these kinds of errors?

推荐答案

已包括在同一个头文件既 file1.c中文件2。 ç。这将pretty多prevent冲突的雏形。

Have the same header file included in both file1.c and file2.c. This will pretty much prevent a conflicting prototype.

否则,这样的错误不能被编译,因为函数的源代码code时,它编译没有编译器可见检测 file1.c中。相反,它也只能相信已经给出的签名。

Otherwise, such a mistake cannot be detected by the compiler because the source code of the function is not visible to the compiler when it compiles file1.c. Rather, it can only trust the signature that has been given.

目前至少理论上,连接物可以是能够检测这样的错配,如果额外的元数据被存储在对象文件,但我不知道这是否是实际上可能的。

At least theoretically, the linker could be able to detect such a mismatch if additional metadata is stored in the object files, but I am not aware if this is practically possible.

这篇关于在头文件中的函数原型不匹配的定义,如何抓住这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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