Search code examples
cstructglobal-variablesdeclarationextern

How to declare an external structure in C


I have already implement an external int in my .h file, with
extern int GLOBAL_RETURNVAL;.

I would like to know how to declare an external structure in the same way (to contain both this int and also a char *).

Trying

extern struct S_GLOBAL 
{
    int GLOBAL_RETURNVAL;
    char *PWD;
};

Solution

  • In this declaration

    extern int GLOBAL_RETURNVAL;
    

    there is declared an object of the type int. An object can have external linkage.

    In this (incorrect) declaration

    extern struct S_GLOBAL  { int GLOBAL_RETURNVAL char *PWD };
    

    you are trying to declare the type specifier struct S_GLOBAL. Structure type specifiers are not allowed to be declared with storage class specifiers (like extern) except using the storage class specifier typedef.

    If you will write for example

    struct S_GLOBAL  { int GLOBAL_RETURNVAL; char *PWD; };
    

    then the data member int GLOBAL,_RETURNVAL of the structure declaration is not the same as the object

    extern int GLOBAL_RETURNVAL;
    

    It seems you want to declare in a header an object of the structure type as for example

    extern struct S_GLOBAL S_GLOBAL;
    

    and in some module to initialize its data members like for example

    struct S_GLOBAL S_GLOBAL = { .GLOBAL_RETURNVAL = GLOBAL,_RETURNVAL, .PWD = NULL };
    

    Or the structure could be declared like

    struct S_GLOBAL  { int *GLOBAL_RETURNVAL; char *PWD; };
    

    and an object of the structure type could be initialized like

    struct S_GLOBAL S_GLOBAL = { .GLOBAL_RETURNVAL = &GLOBAL,_RETURNVAL, .PWD = NULL };