1

All the examples I've found in the net about the usage of getopt_long (for example this here) declare the struct option with the long options as static.

I don't understand why all these examples declare a static variable, I don't see why this should be done and the man pages don't say anything about this either.

Should I declare this variable as a static variable? And why?

Pablo
  • 13,271
  • 4
  • 39
  • 59
  • IMHO in **this** example the `verbose_flag` could be declared as a local variable inside the `main` function. – Jabberwocky Oct 01 '14 at 13:06
  • yes, but I wan't talking about the `verbose_flag` variable, but the `struct option long_options[] ` variable. Why should this variable be declared as static? The linux man page does the same. – Pablo Oct 01 '14 at 13:08
  • 2
    Well: it is not that important. It is only a way to avoid costly initialisation of an automatic array of structures. (since it is basically a lookup-table it is a good idea anyway to have it stored in initialised data section.) – wildplasser Oct 01 '14 at 13:12
  • @Pablo: forget my comment and look at my answer. – Jabberwocky Oct 01 '14 at 13:12
  • Note that, if you declare it with automatic storage, the compiler is likely to just make a copy with static storage and do the equivalent of `memcpy` to the automatic-storage array at runtime. So you've increased the size and runtime of your code and data, for no gain. – R.. GitHub STOP HELPING ICE Oct 01 '14 at 13:55

1 Answers1

2

The reason is efficiency. If you declare the struct option long_options[] not static, it will be constructed at run time upon entry into the main function, but if it is declared as static, it will be constructed at compile time.

But it will work either way.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • ok, this sounds plausible, but ... isn't that a little exaggerated? I mean, how big is this array anyway? 128 bytes? (assuming 4 bytes for every entry and no padding in the struct). – Pablo Oct 01 '14 at 13:17
  • OK, this array is not very big, but it's good practice to declare lookup tables and other fixed data as static if you declare them **inside** a function. – Jabberwocky Oct 01 '14 at 13:32
  • 2
    Note that the good practice is declaring it `static const`, not just `static`. Having `static` without `const` is a code smell: it indicates (falsely, in this case) the existence of global state. – R.. GitHub STOP HELPING ICE Oct 01 '14 at 13:53