volatile variable using in making application

前端 未结 1 718
醉酒成梦
醉酒成梦 2021-01-28 12:21

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 declarat

1条回答
  •  清酒与你
    2021-01-28 12:49

    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.

    0 讨论(0)
提交回复
热议问题