我有下一个代码:
测试.c
#include "a1.h"
int main() {
int a = 8;
foo(a);
return a;
}
a1.h
void foo (int a);
a1.c
int f = 0;
void foo (int a, int b){
f=5+a+b;
return;
}
注意a1.c中的foo比a1.h中定义的原型(prototype)多了1个参数。 编译器不会发出警告或错误,因此覆盖性:
make all
Building file: ../src/a1.c
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/a1.d" -MT"src/a1.d" -o "src/a1.o" "../src/a1.c"
Finished building: ../src/a1.c
Building file: ../src/test.c
Invoking: GCC C++ Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o "src/test.o" "../src/test.c"
Finished building: ../src/test.c
Building target: test
Invoking: GCC C++ Linker
gcc -o "test" ./src/a1.o ./src/test.o
Finished building target: test
在这些情况下我该如何为自己辩护?我知道如果我在 a1.c 文件中添加#include“a1.h”,我会收到错误,但是有没有办法在没有“include”的情况下收到错误?
最佳答案
编译器没有发出警告,因为它不知道 foo(int)
来自a1.h
标题和 foo(int,int)
来自a1.c
文件是相同的功能。 C++ 允许函数重载,因此这两个函数可能会共存。这就是为什么C++编译器无法检测到这个问题,所以你需要等到链接阶段。
如果您使用 C 而不是 C++ 进行编译,则只需包含 a1.h
即可让编译器检测到这种情况。在 a1.c
的顶部文件。
关于编译器不会在函数参数不匹配时发出错误/警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469162/