overexchange overexchange - 1 month ago 16
C Question

Why Linker does not throw, multiple function declaration error?

Following are three files,

/* HANDLERS.H */
#define TRUE 1
#define FALSE 0

/* Functions declarations - included in both UI.C & tiffhandler.c */
int canHandle(char *);
int drawImage(char *);
int saveFile(char *);





/* tiffhandler.c */
#include "HANDLERS.H"

int canHandle(char *fileName){
return TRUE;
}

int drawImage(char *fileName){
return TRUE;
}

int saveFile(char *fileName){
return TRUE;
}





/* UI.C */
#include "HANDLERS.H"
int main(void){
}





that are compiled as,


>gcc HANDLERS.H tiffhandler.c UI.C


My question,

HANDLERS.H
is included in both
UI.C
&
tiffhandler.c
. So, function declarations are included in both.

During linking phase, before
tiffhandler.o
&
UI.o
are linked, Why linker does not complain, by saying, multiple function declarations for each function(say
canHandle
)?

Answer

Because multiple function declarations are perfectly legal. Only multiple function definitions are disallowed.

It is okay to repeat the declaration:

int canHandle(char *);
int canHandle(char *);

But the following is incorrect since it repeats a definition:

int canHandle(char *fileName){
    return TRUE;
}

int canHandle(char *fileName){
    return TRUE;
}

The prohibition against multiple definitions of the same function is enforced by both the compiler (inside a single translation unit) and the linker (across multiple translation units).