Delan Azabani
Delan Azabani

Reputation: 81384

extern without type

If the syntax of extern is

extern <type> <name>;

how do I extern if I have an unnamed, single use struct:

struct {
    char **plymouthThemes;
    char *plymouthTheme;
} global;

I've tried

extern global;

without any type, and it doesn't work.

Or, do I have to name the struct?

Upvotes: 6

Views: 2398

Answers (3)

lemic
lemic

Reputation: 197

The idea is that you need to declare only one but still need to define the variable in each other file that uses it. The definition includes both the type (in your case a header define structure - which therefore need include) and the extern keyword to let know the compiler the declaration is in a different file.

here is my example

ext.h

struct mystruct{
    int s,r;
};

ext1.c

#include "ext.h"

struct mystruct aaaa;

main(){
    return 0;
}

ext2.c

#include "ext.h"

extern struct mystruct aaaa;

void foo(){
    aaaa;
}

ext3.c

#include "ext.h"

extern struct mystruct aaaa;

void foo2(){
    aaaa;
}

Upvotes: 1

Vovanium
Vovanium

Reputation: 3888

If you do not want to name a struct there's common method:

--- global.h: (file with global struct definition):

#ifdef GLOBAL_HERE /* some macro, which defined in one file only*/
#define GLOBAL
#else
#define GLOBAL extern
#endif

GLOBAL struct {
    char **plymouthThemes;
    char *plymouthTheme;
} global;

---- file1.c (file where you want to have global allocated)

#define GLOBAL_HERE
#include "global.h"

---- file2.c (any oher file referencing to global)

#include "global.h"

The macro GLOBAL is conditionally defined so its usage will prepend a definition with "extern" everywhere except source where GLOBAL_HERE is defined. When you define GLOBAL_HERE then variable gets non-extern, so it will be allocated in output object of this source.

There's also short trick definition (which set in single .c file where you allocate globals):

#define extern

which cause preprocessor to remove extern (replace with empty string). But do not do it: redefining standard keywords is bad.

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

You need to name your struct and put it in a .h file or included the definition by hand in every source file that uses global. Like this

///glob.h
    struct GlobalStruct
    {
       ///char** ...
       ///
    };

///glob.cpp
   #include "glob.h"
   struct GlobalStruct global; 

///someOtherFile.cpp
#include "glob.h"

extern struct GlobalStruct global; 

Upvotes: 5

Related Questions