关于extern函数时参数类型不匹配GCC编译如何可以生成告警或是错误的问题


有以下三个文件,两个.C文件,一个.h头文件,main.c会引用test.h,并调用testProtoType()函数。
test.c


 int testProtoType(unsigned int a)
{
    printf("0x%x", a);
    return 0;
}

test.h


 extern int testProtoType(unsigned short a);

main.c


 #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
int main()
{   
    long x = 0x12345678;
    testProtoType(x);

    return 0;
}

GCC进行编译(并不会报任何的编译告警和错误):

gcc.exe -Wall *.c -o main

GCC的版本号是:

gcc (GCC) 3.4.2 (mingw-special) Copyright
(C) 2004 Free Software Foundation, Inc. This is free software; see the
source for copying conditions. There is NO warranty; not even for
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

执行main后,结果如下:

0x5678 Press any key to continue . . .

生成的结果并不是0x12345678,而是按照头文件中声明的参数类型short进行了截断,但是GCC在编译链接时并没有产生告警或是错误,这是什么原因,有什么可让GCC产生编译告警或是错误的方法吗?

c gcc

雪羽乂鈴音 9 years, 7 months ago

这事和 extern 没关系,GCC本来就不会主动报这种警告,即便你把两个程序写在一个文件里也这样。
要想让GCC报警告,加一个 -Wconversion 参数(这个选项缺省是关闭的)。

sybdcz answered 9 years, 7 months ago

Your Answer