Why should I use the extern
keyword in the following code:
header.h
float kFloat; // some say I should write 'extern float kFloat;', but why?
file.c
#include <stdio.h>
#include "Header.h"
float kFloat = 11.0f;
main.c
#include <stdio.h>
#include "Header.h"
int main(int argc, const char * argv[])
{
printf("The global var is %.1f\n", kFloat);
return 0;
}
This code works. The global Variable kFloat defaults to external linkage and static lifetime.
Output is:
The global var is 11.0
I don't understand in which case the problem would occur, can anyone give me an example where it would crash?
extern float kFloat;
declares kFloat
without defining it.
but:
float kFloat;
also declares kFloat
but is a tentative definition of kFloat
.
Adding extern
just suppresses the tentative definition. In a header file you only want declarations, not definitions.
If the tentative definition is included in several source files, you will end up having multiple definitions of the same object which is undefined behavior in C.