Question

I m using c18 compiler and i am declaring extern variable x in project.h

and in

project.h

  extern unsigned int x;

file1.c

 #include"project.h"

 foo1()
 {   
     x=200; 

 }

and in foo2.c

  #include"project.h"
foo2()
  {
     printf("%d",x);

  }

foo1 executes first ahead of foo2 I have made extern declaration in project.h and i defined x in foo1.c

should the foo2.c must have 200 as x value right.?

Était-ce utile?

La solution

If those two files, plus a header containing only extern int x;, are all you have, it shouldn't even compile (well, it might compile but it won't link).

extern int x; lets the compiler know that x exists somewhere but doesn't actually bring it into existence.

The way this is normally done is to define the variable somewhere and declare it wherever it's used, something like:

project.h:
    extern int x;         // declare

file1.c:
    #include "project.h"  // declare in the header
    int main (void) {
        x = 200;
        printf ("x is %d\n", x);
        return 0;
    }

file2.c:
    #include "project.h"  // declare in the header
    int x;                // define it.

Autres conseils

Use printf("%d\n", x); to print the variable instead of the character 'x'.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top