why 'extern' was used in the noui.h file?

1

When i review the source code, i find that the noui.h is a header file, but the method noui_connect has been declared by key words 'extern'. i think there is no need to do this.

extern void noui_connect();

jinsong ai

Posted 2018-08-31T09:27:49.033

Reputation: 105

Answers

3

extern before function prototypes does not have any effect. If it were a variable, it’d be needed to specify that the variable was declared somewhere else.

void noui_connect();

void noui_connect() {/*something*/}

^^^The compiler can easily find which is the prototype and which is the implementation of the same function. However,

// main.h
int a;
// main.c
#include "main.h"
int a = 5;
// util.c
#include "main.h"

^^^The compiler might create two symbols. One in main.c, one in util.c. To prevent creation of another variable, the extern keyword is used to leave the variable to the linker, the final step at compiling.

On the contrary, the function prototypes, not the implementations are put in header files, which are always left to the linker. Because that's the way function prototypes are designed, they don't need extern.

If you see extern before function prototypes, that's pure coding style, probably to be consistent with other extern variables.

MCCCS

Posted 2018-08-31T09:27:49.033

Reputation: 5 827

Not just consistency, but also clarity. It explicitly signifies to the programmer "The function is not being defined here". Even though it is obvious to the compiler does not mean it must be obvious to developers.Pieter Wuille 2018-08-31T11:17:15.457