How to access the correct global variable in C?

lets say that I have a global var GLOBAL in main.c, but my main.c has #include "other.h". But other.h also has a global var GLOBAL.

How to tell the compiler what I meant when I write GLOBAL basically. Is there a "this" keyword that I can use?

+3
source share
7 answers

I assume that you defined the variable in the program, and not in the preprocessor, using #define.

If you want to refer to what was created in main.c, just type global. To access those from the header file, use the extern keyword.

It's better to declare them as two different variable names, though, to be honest.

-1

C . C , . , -, . "". .

, C-

int i;
int i;
int i;

C ( ++), , .

, ( , ) (, GLOBAL then?), , ( ). C. , .

, "other.h, ", . "" ? other.h? ? , " ". ... , : .h?

+10

. : ( ), , / , , .

+5

, /. . MODULE1_state, MODULE2_state ..

, . static. , , extern. . / , - , ++, Java, # ..

:

.h:

#ifndef MODULE_H /* Header guard */
#define MODULE_H

/* Declarations for entities that CAN be accessed by other modules,
   i.e. "public". */
extern int MOD_publicVariable;
extern void MOD_publicFunction(int arg);

#endif // MODULE_H

module.c:

/* Definitions for entities that CAN be accessed by other modules,
   i.e. "public". */
int MOD_publicVariable = 42;
void MOD_publicFunction(int arg) {...}

/* Declarations for entities that CAN'T be accessed by other modules,
   i.e. "private". */
static double MOD_privateVariable = 12.34;
static void MOD_privateFunction1(void);
static void MOD_privateFunction2(void);

/* Function definitions. */
void MOD_privateFunction1(void) {
     int localVariable; /* This doesn't need the module prefix. */
     ....
}

void MOD_privateFunction2(void) {
     ....
}

(MOD_) . , . , , // OO.

, , extern vs. static.

, C , .

EDIT: , (.. "private"). , "" "setter" / "getter".

+2

. , , . , .

0

, , (, , )?

0

First of all, if this is a problem, firstly, you use a crappy library and should rewrite / switch if possible. If you cannot, you can do something like this:

other.h:

int GLOBAL;
//...other stuff

main.c

int GLOBAL;
#define GLOBAL OTHER_GLOBAL
#include "other.h"
#undef GLOBAL

int main(int argc,char** argv)
    {
    printf("%i %i",GLOBAL,OTHER_GLOBAL);
    getchar();
    return 0;
    }

however, if, as can be seen from the tables, GLOBAL #defineed, this may not work. (But still worth a try.)

0
source