简体   繁体   中英

Making a local variables to Global so the main function can access it in C

I have a code in which I have the function tilt_left there are some variable that I want to make it available for the main .

But I have no idea how to do that; I think it's generally very easy to do that.

Following is my code.

unsigned char sync, camera_address;

#include <stdio.h>

void tilt_left();

void config() {
    sync = 0xFF;
    camera_address = 0x01;
    printf ("The sync code is %x %x", sync, camera_address);
}

void tilt_left() {
    unsigned char command1, command2, Data1, Data2;
    command1 = 0x00;
    command2 = 0x04;
    Data1    = 0x3F;
    Data2    = 0x00;
}

void main() {
    
    unsigned char checksum;

    config();
    tilt_left();

    checksum = camera_address + command1+command2+Data1+Data2;
    
    checksum %=100;
    printf ("The sync code is %x %x %x %x %x %x %x", sync, camera_address,command1, command2, Data1,Data2,Checksum);
    //  return 0;
}

"... are some variable that I want to make it available for the main."

In general that is a very bad idea - global variables shall be avoided when possible. If you want to access the variables in main , you define them in main .

Like:

void tilt_left (unsigned char *command1,  // Use pointers so that the
                unsigned char *command2,  // function can write to the
                unsigned char *Data1,     // pointed-to variable
                unsigned char *Data2)
{
  
  *command1 = 0x00;
  *command2 = 0x04;
  *Data1    = 0x3F;
  *Data2    = 0x00;
}

void main(){
    
  unsigned char checksum;
  unsigned char command1, command2, Data1, Data2;    
  
  ...

  // Pass address-of the variables
  tilt_left(&command1, &command2, &Data1, &Data2);

To declare a global variable you just have to declare it outside the main (and outside any other function)

int global_variable = 0;

int main()
{
    /* do stuff */
}

Edit

But how to call a local variable of any other function to the main

You can't do that. When a function returns, its activation record is deallocated and the local variables are lost. What you can do, is passing a pointer to a variable (stored in main, or in general, in the calling function) and access it from another function.

#include <stdio.h>

void function(int *var);

int main()
{
    int var = 0;

    /* Passing the pointer to var as parameter */
    function(&var);

    /* Prints 5 */
    printf("%d\n", var); 
}

void function(int *var)
{
    /* Prints 0 */
    printf("%d\n", *var); 

    /* Dereference the pointer and assign a new value to the variable */
    *var = 5; 
    return;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM