質問

I have a function in source file 1 : Source file 1:

 function in Source file 1.
    Code:
        char day[7];
    f1:
         {  
           ....
           ....
           ....
        after some work fill the
           day[0]= random number;
           .
           .
           .
           .
           day[6]=random number;     


           }     

Quote:
Source file 2:

f2:

{
extern dayval[];

//do stuff

}

And now i want to access those day[7] values from array in source file 2.

If i declare array as extern in source file 2 immediately after f1 in source file is executed will the values remain same or will it be zero

Well forgive my stupidity i have started learning C language just now and it's been Quite a hell of ride Smile. I hope you guys will enlighten me with your suggestions

Which is the best way to access data.I'm working on embedded systems and some say pass by reference is a good option.I would be delighted to have your views on it.

Regards

役に立ちましたか?

解決

Yes, it can be solved by declaring it as an extern variable, but it needs to be global in source1.c too. Local variables cannot be accessed from outside their scopes, at least not by name.

So, in source1.c:

char day[7];

void function1(void)
{
  day[0] = ...;
  /* and so on */
}

then in source2.c:

extern char day[7];

void function2(void)
{
  printf("oh, source1 has set day[0] to %c\n", day[0]);
}

of course, you must make sure that function1() from source1.c runs before function2() from source2.c, in order to initialize the array.

You could have a separate main.c that does:

int main(void)
{
  function1();
  function2();
  return 0;
}

Then compile them all together, using something like this (assuming gcc in a Unix-type environment):

$ gcc -o myprogram main.c source1.c source2.c
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top