compiler isn't issue error/warning in mismatch function parameter

723 Views Asked by At

I have the next code :

test.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;
}

Pay attention that in a1.c foo has 1 more parameter than the prototype defined in a1.h. The compiler isn't issue a warning or an error and so as coverity :

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

How can I defend myself in those cases ? I know that if I will add #include "a1.h" in the a1.c file I will get an error but is there a way to get an error without the "include " ?

2

There are 2 best solutions below

0
On

You're overloading foo. The version with only one parameter is never defined, hence you should get a linker error when using it.

How can I defend myself in those cases ?

You can't defend yourself from function overloading. Just make sure that you've got the same signature in both the header as the source file.

0
On

Compiler isn't issuing a warning because it does not know that foo(int) from a1.h header and foo(int,int) from a1.c file is the same function. C++ allows functions to be overloaded, so both functions could potentially coexist. That is why C++ compiler cannot detect this problem, so you need to wait until the linking stage.

If you were compiling using C, not C++, you could have the compiler detect this condition simply by including a1.h at the top of a1.c file.