pmor
pmor

Reputation: 6286

Calling implicitly declared function with too few arguments: why there is no linker error?

Example:

/* lib.c */
#include <stdio.h>

int f1(int a)
{
        printf("%d\n", a);
        return 0;
}

/* t3.c */
int main()
{
        f1();
        return 0;
}

gcc -c -o lib.o lib.c && gcc t3.c lib.o && ./a.exe
t3.c: In function 'main':
t3.c:3:2: warning: implicit declaration of function 'f1' [-Wimplicit-function-declaration]
    3 |  f1();
      |  ^~
1

clang -c -o lib.o lib.c && clang t3.c lib.o && ./a.exe
t3.c:3:2: warning: implicit declaration of function 'f1' is invalid in C99 [-Wimplicit-function-declaration]
        f1();
        ^
1 warning generated.
1

Questions:

  1. Why this even compiles (i.e. a.exe is generated)?
  2. Why there is no linker error like error: too few arguments to function call f1, expected 1, have 0?
  3. Is it a constraint violation?

Upvotes: 2

Views: 171

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

Why this even compiles (i.e. a.exe is generated)?

The compiler supports backward compatibility. Before the C99 Standard a function may be called without providing its declaration. The C compiler does not produce mangled names for functions as C++ compilers do.

Why there is no linker error like error: too few arguments to function call f1, expected 1, have 0?

The linker found the external name f1. So the reference to f1 was resolved. The linker does not check how the function is called.

Upvotes: 1

Related Questions