C - gcc: no compiler warning with different function-declaration/implementation

有些话、适合烂在心里 提交于 2019-12-02 09:47:33

问题


I try to figure out why my c-compiler gives me no warning/error with following (simplified) code.

The function-declaration have no parameters while the function-implementation have parameters:

some.h:

void foo();

some.c:

static uint32_t count = 0; 

void foo(uint32_t num) {
    count += num;
    print("Count: %u");
}

main.c:

foo(100);
foo();

Output:

Count: 100
Count: 100

Compiler for target build:

gcc-arm-none-eabi-4_9-2015q1-20150306-win32

Linker for target build:

gcc-arm-none-eabi-4_9-2015q1-20150306-win32

Compiler-Flags:

-Wall -Werror -DuECC_CURVE=uECC_secp256r1 -DMEMORY_CHECK -DDEBUG -Os -g3 -DBACKTRACE


回答1:


Because of backward compatibility, a declaration like

void foo();

doesn't declare a function that takes no argument, it declares a function which takes an unknown number of arguments of unknown type.

That means both your calls are correct, and the compiler can't really warn you about it.

The other problematic thing is that the declaration in the source file actually matches the declaration in the header file, it just makes it more precise. Therefore you will not get a warning or error there either.




回答2:


In C this function declaration

void foo();

means that there is nothing known about the function parameters in the point of the declaration.

The types and number of the parameters are deduced from a function call.

As for your program then this call

foo();

has undefined behavior because the number of parameters and the number of arguments mismatch.



来源:https://stackoverflow.com/questions/39411110/c-gcc-no-compiler-warning-with-different-function-declaration-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!