1

I am thinking of using a global constant struct to manage configuration of some sub-systems. This means that I would like to use something like:

const struct SystemConfig {
  .channels = 5,
  .mode = NORMAL_MODE,
} SYSTEM_CONFIG;

And later use it in my code like usual:

...
numberOfChannels = SYSTEM_CONFIG.channels;
mode = SYSTEM_CONFIG.mode;
...

I would like to use this approach to skip #define's.

My question is if the compiler will realize this and replace the values with their respective values when it is compiled, considering everything is constant?

EDIT: Sorry for tagging both C and C++, it's fixed now and my question relates only to C. The compiler I use is GCC with a ARM Cortex-M4 target.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Niklas Norin
  • 355
  • 1
  • 3
  • 9
  • Give it a try and see! – Nocturno Feb 15 '13 at 14:06
  • The only way to find out is to look at the generated assembler code. – Some programmer dude Feb 15 '13 at 14:07
  • 2
    `...if the compiler will...` which compiler? And since it's tagged with both C and C++, which language? – Mike Feb 15 '13 at 14:08
  • 1
    Even if the compiler doesn't special case it, how much difference is it going to make to runtime of your code in practice? The mechanism is quite neat and tidy; use it if you think the notational clarity is worthwhile (it might well be worth it). – Jonathan Leffler Feb 15 '13 at 14:54
  • @Niklas Norin Are you familiar with design patterns? Have you considered the Singletone pattern, it quit good fits to your needs, as you described them in your question – spin_eight May 08 '13 at 17:43

1 Answers1

0

I would use static const so your struct is not visible at link level. For example:

static const unsigned int channels = 5;
unsigned numberOfChannels = channels;

would definitely be optimised by a compiler. So I can't see why any modern compiler would be unable to optimise your example either.

If it was me I would find the compiler option to output the code it was laying down. It's an interesting exercise.

Trygve Laugstøl
  • 7,440
  • 2
  • 36
  • 40
AlgebraWinter
  • 321
  • 2
  • 3