WIlopu
WIlopu

Reputation: 47

A module's global variable

I have a module of 2 files: the header (module.h) and the implementation (module.c). The function of this module are used in another .c file.

I want a module to have a global variable that won't get reinitialized every time a function of this module is called. Said variable will be modified only from within the module.

To give you a better picture:

module.c:

int glob_var;
int func(); //It modifies `glob_var`'s value

main.c:

#include "module.h"
func();

How can I go about this?

Upvotes: 1

Views: 2001

Answers (3)

hitman47
hitman47

Reputation: 237

module.c:

static int glob_var;
int func(); //It modifies glob_var's value

main.c:

#include "module.h"
func()

Upvotes: 0

user2393819
user2393819

Reputation: 26

you can also use static modifier to your glob_var.

Upvotes: 1

P.P
P.P

Reputation: 121407

Said variable will me modified only from within the module

Since the variable is going to be modified/needed only in func(), you don't need it as a global variable. Declare it as static within func().

int func(void)
{
   static int var = 0;
   /* Do stuff */

   /* Modify 'var' */
}

In general, you should avoid global variables whenever you can. In your case, you don't need it. Notice that var will not be reinitialized when func() is called multiple times as it's a static variable.

Upvotes: 2

Related Questions