Arun Gupta
Arun Gupta

Reputation: 808

Defining Global variable, Which is going to be used by multiple .c files

I needed to define several variables (Global variables), which are going to be used by many .c files. Variables like String array, File Pointer, Int etc.

Situation : FileX.h

Different c files(FileA, FileB, Filec, FileD) compiled with -c option individually(FileX.h have been included by all) then some of the files compiled again by combining them. When these are compiled individually No error pop up, but When they are compiled in a group (FileA.o, FileB.o and FileC.o), It pop ups Error. Is there any way to solve it. I thought of solving this with extern but seems this would also pop up error also.

Any suggestion please ?

I don't want to define variable in each .c file

I have String array so i don't want to define them every file

Upvotes: 0

Views: 84

Answers (1)

RedX
RedX

Reputation: 15175

I'm assuming you get a multiple definitions error because your header looks like

global_variables.h

int global_a = 10;
int const global_b = 20;

What you need is

global_variables.h

extern int global_a;
extern int const global_b;

global_variables.c

int global_a = 10;
int const global_b = 20;

Edit: Further explanation:

Now in all your other files that need the global variables all you need is:

other_file.c

#include "global_variables.h"
void some_func(void){
   global_a = 5; /* ready to use */
}

other_awesome_file.c

#include "global_variables.h"
/* and now you can use all globals */

Upvotes: 1

Related Questions