0

I am new in this field. Previously I was doing microcontroller programming where I used volatile variables to avoid compiler optimization. But I never saw such volatile declaration before variable declaration. Does it mean compilation is done without any optimization in Arago build. Here I have two questions.

  1. How can I enable different types of optimization during compilation like speed and space optimization in Angstrom build?

  2. If it is already an optimized compilation, why do we not need volatile declarations?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Embedded Programmer
  • 519
  • 4
  • 8
  • 22

1 Answers1

2

If you are using gcc for compilation then add/modify CFLAGS

  • -O2 or -O3 to enable a bunch of generic performance optimisations.

  • Os to enable code size optimisations.

A long list of flags that control individual gcc compiler optimisation options is available here.


Most often volatile is used NOT for optimising the code, but to ensure validity of data.

The declaration of a variable as volatile tells the compiler that the variable can be modified at any time externally to the implementation by

  • the operating system
  • another thread of execution
    -- interrupt routine
    -- signal handler
  • underlying hardware

As the value of a volatile-qualified variable can change at any time, the actual variable must always be accessed whenever the variable is referenced in code.

This means the compiler cannot perform optimizations on the variable. Marking a variable volatile forces the compiler to generate code that ignores the variable in the CPU register and actually reads the underlying memory/hardware-register mapped at the address referred-to by the variable.

Also checkout the various aspects of using volatile along-with compiler optimisations.

Community
  • 1
  • 1
TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
  • 3
    Actually, `volatile` has nothing to do with CPU caches. It only tells the *compiler* that it cannot keep a temporary copy of the value of the variable because it might change at any time; that whenever the variable is used, the compiler must access the underlying memory. – Nominal Animal Sep 08 '13 at 02:32
  • @NominalAnimal Updated the answer to remove any confusion caused by the word `cache`. – TheCodeArtist Sep 08 '13 at 02:36
  • Yup, looks good now. It might be useful to note that `volatile __asm__()` behaves similarly, as a memory barrier, stopping the compiler from moving memory accesses across the inline assembly (which it may do without the `volatile` keyword); drilling in the fact that it is a directive for the compiler what kind of memory accesses it should generate, but I'm quite happy with your answer as it is. – Nominal Animal Sep 08 '13 at 03:10
  • Thanks to all of you. – Embedded Programmer Sep 09 '13 at 09:26