Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to access C variables in .c files ?

Status
Not open for further replies.

JaMe

Junior Member level 1
Joined
Nov 8, 2006
Messages
19
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Indonesia
Activity points
1,406
I have variable called "Timer1" in file "main.c".
The problem is, is there any way to access those variable in other file, e.g, in file "init.c" ?
 

variable in C

Are main.c and init.c compiled into one executable?
If main() calls init(), then the call could pass a pointer to Timer1.

Code:
#include <stdio.h>

void init(int *value)
{
  printf(" Value = %d\n", *value);
  *value *= 2;
  printf(" Value = %d\n", *value);
}

int main(void)
{
  int Timer1 = 123;
  printf("Timer1 = %d\n", Timer1);
  init(&Timer1);
  printf("Timer1 = %d\n", Timer1);
  return 0;
}
Output:
Code:
Timer1 = 123
 Value = 123
 Value = 246
Timer1 = 246
 

Re: variable in C

hi

in the file init.c put
extern datatype Timer1;
this is if the variable Timer1 is global variable in file main.c

For more details check the keyword extern.
**broken link removed**


Salam
Hossam Alzomor
www(.)i-g(.)org
 

    JaMe

    Points: 2
    Helpful Answer Positive Rating
Re: variable in C

you can't access it unless you define the variable outside main function.




JaMe said:
I have variable called "Timer1" in file "main.c".
The problem is, is there any way to access those variable in other file, e.g, in file "init.c" ?
 

Re: variable in C

in "init.c"

extern int Timer1;

void init(void)
{
Timer1 = 0;
}

//----------------------------------------
in "main.c"

int Timer1;

extern void init(void);

int main(void)
{
init();

//other codes

return 0;
}
 

Re: variable in C

The variable Timer1 should be global
 

variable in C

U need the extern statement. That plus the function prototype tell the compiler/likerhow to set up the call, what to return from it, what the storage spaces required are and also. extern tells the compiler it will find the function (or a variable) in another file.
 

variable in C

One way of doing this is to create a main.h, decalre this variable as extern and then include the main.h in the init.c file. This is needed if the compiler enforces ansi stds strictly. Otherwise, make sure that u link both files after compilation, use the extern keyword directly in your init.c file.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top