lulyon
lulyon

Reputation: 7225

variable in two source file

I have read this exam code.

"a.c":

int global_1 = 100;

"b.c":

extern int global_1;
int global_2 = global_1 * 2;

int main()
{
    return 0;
}

gcc give “error: initializer element is not constant"

I do not write this code, but I want to know why and how to fix.

Thanks.

Upvotes: 2

Views: 102

Answers (2)

Sergey L.
Sergey L.

Reputation: 22542

The problem you are facing is that in order to initialise a variable (global_2 here) it's value (or all values of what it depends on, in your case global_1) need to be known.

When you initialise a variable in a function then it's value only needs to be known at runtime and that is generally the case or you will get an undefined symbol error during compile or link time.

Globals need to be initialised by the compiler during compile time.

extern int global_1;

Says to the compiler that global_1 exists, but not in this compilation unit. It will be accessible after linking. You can use it in functions, but the linker needs to link it first with an object file that actually contains it.

Thus the compiler is unable to initialise it at compile time resulting in the error you see. Linking comes after compiling.

If you need to initialise globals that reference globals in a different compilation unit then you will need to do this in a function. For example the first stem in main().

Upvotes: 3

alk
alk

Reputation: 70911

The error says it all: Initialisers need to be constants.

To fix this you might like to modify your code like this:

int global_2 = 0;

int main()
{
  global_2 = global_1 * 2;

Upvotes: 1

Related Questions