I am a newbie and trying to understand program in C.
In the program, there is one header file typedef.h
which declares typedef struct { int i; char b;} rdi;
Then there are 3 folders and each folder has several programs that do a particular task and each folder has one header file. In the header file of each 3 folders it has
#include typfedef.h
and then declared
extern rdi *rdi_x;
In all 3 folders it did it. But I do not see it any where in the program defined:
rdi rdi_x;
My question is whether it is not required to define rdi rdi_x;
in the program.
As I understand from c text books, somewhere in the program it needs to define rdi rdi_x;
or my understanding is not good.
As I understand from c text book, somewhere in the program it needs to define
rdi rdi_x;
or my understanding is not good.
You need to define rdi_x
only if it is used. Just declaring the variable does not require that it be defined.
Take a much simpler case of one .c file:
Program that fails to build:
extern int i;
extern int j;
extern int k;
int main()
{
k = 10;
}
This program will fail to build since k
is used. If we provide the definition of just k
, it will build just fine.
Program that builds successfully:
extern int i;
extern int j;
extern int k;
int main()
{
k = 10;
}
int k;
Here, i
, and j
are declared but not used. Hence, they need not be defined.
Firstly, the #include
in the three source files will be #include "typfedef.h"
, not #include typfedef.h
. The double quotes are required.
Second, extern rdi *rdi_x
is a declaration, but not a definition. It can be repeated in any number of source files (or in header files), and will never result in rdi_x
being defined.
It is necessary to also create a corresponding definition, for example providing the same declaration without the extern
keyword, viz.
rdi *rdi_x;
Note the *
is still present. Your description incorrectly suggests that a definition rdi rdi_x;
(leaving out the *
) is required.
Bear in mind that, formally, a definition is a type of declaration. The extern rdi *rdi_x
is a declaration but not a definition - which is why it can be repeated. The declaration rdi *rdi_x
is a corresponding definition - and is subject to the "one definition rule" - in other words, such a definition must be supplied once (and only once) among all compilation units in a project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With