简体   繁体   中英

Global vs. local static variable for shell environment variables

I'm implementing a simple shell and I want to be able to set environment variables through the shell. Using a simple syntax such as set var = hello

I have a struct like this to represent one env variable:

typedef struct {
    char *name;
    char *value;
}

I'm thinking of creating a dynamic array of the above struct to hold all environment variables. The problem is I'm not sure how to implement this properly.

Right now, I'm not sure if I should make the array static inside a function or a global variable. Which one would be better? and why?

It entirely depends on where the variables need to be accessed from. If they're only needed in a single function, then a static local variable makes the most sense. If they're needed "file-wide" then a file global (that is still static) makes the most sense. Otherwise, a global.

The other option, better for future expansion, would be to create a file-static variable set with accessor functions to get and set name/value combinations, and use that API everywhere else. That lets you change the storage mechanism later to something more efficient if, say, you suddenly needed to store lots of name/values pairs (say, into a b-tree instead of an array).

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