Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern without type

Tags:

c

extern

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?

like image 942
Delan Azabani Avatar asked Nov 08 '10 11:11

Delan Azabani


People also ask

What is extern type in C++?

The extern keyword tells the compiler that a variable is defined in another source module (outside of the current scope).

Can we declare structure as extern?

You cannot extern a struct like that! declare the structure in a single . h file and include that . h file wherever you need to use the structure.

Can we initialize extern variable in C?

You can initialize any object with the extern storage class specifier at global scope in C or at namespace scope in C++. The initializer for an extern object must either: Appear as part of the definition and the initial value must be described by a constant expression; or.

Why extern keyword is used in C?

“extern” keyword is used to extend the visibility of function or variable. By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy. Variables with “extern” keyword are only declared not defined.


2 Answers

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; 
like image 163
Armen Tsirunyan Avatar answered Sep 22 '22 15:09

Armen Tsirunyan


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.

like image 41
Vovanium Avatar answered Sep 21 '22 15:09

Vovanium