I have a header file that looks like
header.h
int TOS;
This file is being included by just one code file
code.c
#include "header.h"
TOS=0;
When compiling code.c GCC issues a warning
code.c:3:1: warning: data definition has no type or storage class [enabled by default]
code.c:3:1: warning: type defaults to ‘int’ in declaration of ‘TOS’ [enabled by default]
I fail to understand the cause of this warning. Isn't it equivalent to declaring and defining TOS in code.c? i.e.
code.c
int TOS;
TOS=0;
It is because you define TOS
in the global scope, which need you to define the type of TOS
(it is an declaration), if no type was given, by default it is int
.
This will cause an conflicting type error
,
char x;
x = 0;
The correct way to forward a variable in a header file would be
extern int TOS;
without the extern
this could otherwise result that TOS
is allocated in several compilation units (.o files).
You'd then give a definition in one .c file as
int TOS;
This would then reserve space for it and since it is a variable in global scope it also would initialize it to 0
. If you want to make this initialization explicit or if you want it to be to another value than 0
, the correct syntax for initialization (and not assignment) is
int TOS = 54;
Modern C doesn't allow the syntax that you seem to have inherited from somewhere, namely a definition of a global variable with implicit type int
.
TOS=0
is not an assignment, it's a declaration with an initializer (i.e: a definition). int TOS;
is a tentative definition with external linkage. When the linker links several translation units together, it collapses the corresponding object (=memory for a variable). As said elsewhere, the default type of int
is a C89 feature absent from later editions of the standard.