Coconop Coconop - 3 months ago 11
C Question

Why don't I have "undefined reference to"?

I faced a similar problem in my (big) project.

//# include <string.h> // not included

void foo(char * str, const char * delim)
{
char * tok = strtok(str, delim);
// warning ^ "assignement makes pointer from integer without a cast"

// [...]
}


The answer (just add
#include <string.h>
to have the prototype of
strtok
) solved the issue indeed.

However, due to my poor compiler/linker knowledge, I fail to understand how the process accepts a function that have not been prototyped.
I'd rather expected the error
undefined reference to function 'strtok'
which is typical when you forget to include the right header.

[EDIT] I understand why this question has been marked as duplicate but I do think it is different : I am aware of "good practice" regarding includes, I am just wondering about compiler's behavior. However I admit that I can found (part of) an answer to my question in this post: Are prototypes required for all functions in C89, C90 or C99? or this one: Must declare function prototype in C?

Answer

While linking your binary, unless explicitly mentioned, your binary is linked with the default C standard library (glibc, for example) anyways, where the function is defined.

So, when you miss the header file containing the declaration, you end up with the warning (in case the function prototype has a mismatchnote) but during linking time, due to the presence of the default C library, the program is successfully linked anyway.

FWIW, according to C11, support for implicit function declaration has been dropped but most compilers support the bad behavior to keep the backward compatibility for the legacy code.


NOTE:

Implicit function declaration: Earlier, (before C99, AFAIK), the standard did not mandate for a function to have the forward declaration. In case, a function would have been used without a forward declaration, it was assumed to return int and accept any number of incoming parameters.