Use of #pragma in C

前端 未结 10 1719
囚心锁ツ
囚心锁ツ 2020-11-27 09:32

What are some uses of #pragma in C, with examples?

相关标签:
10条回答
  • 2020-11-27 09:58

    Putting #pragma once at the top of your header file will ensure that it is only included once. Note that #pragma once is not standard C99, but supported by most modern compilers.

    An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */)

    0 讨论(0)
  • 2020-11-27 10:02

    what i feel is #pragma is a directive where if you want the code to be location specific .say a situation where you want the program counter to read from the specific address where the ISR is written then you can specify ISR at that location using #pragma vector=ADC12_VECTOR and followd by interrupt rotines name and its description

    0 讨论(0)
  • 2020-11-27 10:07

    This is a preprocessor directive that can be used to turn on or off certain features.

    It is of two types #pragma startup, #pragma exit and #pragma warn.

    #pragma startup allows us to specify functions called upon program startup.

    #pragma exit allows us to specify functions called upon program exit.

    #pragma warn tells the computer to suppress any warning or not.

    Many other #pragma styles can be used to control the compiler.

    0 讨论(0)
  • 2020-11-27 10:08

    #pragma startup is a directive which is used to call a function before the main function and to call another function after the main function, e.g.

    #pragma startup func1
    #pragma exit func2
    

    Here, func1 runs before main and func2 runs afterwards.

    NOTE: This code works only in Turbo-C compiler. To achieve this functionality in GCC, you can declare func1 and func2 like this:

    void __attribute__((constructor)) func1();
    void __attribute__((destructor)) func2();
    
    0 讨论(0)
  • 2020-11-27 10:10

    #pragma is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.

    The one I regularly use is #pragma pack(1) where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.

    Pity we don't have a #dogma yet. That would be fun ;)

    0 讨论(0)
  • 2020-11-27 10:12

    To sum it up, #pragma tells the compiler to do stuff. Here are a couple of ways I use it:

    • #pragma can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:

      #pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
      

      An older version of libportable does this portably.

    • #pragma once, when written at the top of a header file, will cause said header file to be included once. libportable checks for pragma once support.

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