top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why we should not define global variables in header files only extern?

0 votes
413 views
Why we should not define global variables in header files only extern?
posted Jul 10, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

You should never not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

Suppose if you define a variable called int my_int in header file my_header.h and you system has more then one .c file called file1.c and file2.c both are including my_header.h. Then variable my_int would be declared twice and can create unexpected result. Better approach would be to define my_int in one of the .c file and create the exterm int my_int in the header file.

I hope it should help you.

answer Jul 13, 2014 by Salil Agrawal
Similar Questions
+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

+7 votes

In lot of C++ code in my company I see extern C code something like

extern "C"
{
    int sum(int x, int y)
    {
        return x+y;
    }
}

Please explain the significance of this?

...